blob: cc0ea1eac57299fe0286713c32445ae41201383c [file] [log] [blame]
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001/*
2**
3** Copyright 2008, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18// Proxy for media player implementations
19
20//#define LOG_NDEBUG 0
21#define LOG_TAG "MediaPlayerService"
22#include <utils/Log.h>
23
24#include <sys/types.h>
25#include <sys/stat.h>
Gloria Wang7cf180c2011-02-19 18:37:57 -080026#include <sys/time.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080027#include <dirent.h>
28#include <unistd.h>
29
30#include <string.h>
Mathias Agopian6f74b0c2009-06-03 17:32:49 -070031
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080032#include <cutils/atomic.h>
Nicolas Catania14d27472009-07-13 14:37:49 -070033#include <cutils/properties.h> // for property_get
Mathias Agopian6f74b0c2009-06-03 17:32:49 -070034
35#include <utils/misc.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080036
Mathias Agopian75624082009-05-19 19:08:10 -070037#include <binder/IPCThreadState.h>
38#include <binder/IServiceManager.h>
39#include <binder/MemoryHeapBase.h>
40#include <binder/MemoryBase.h>
Mathias Agopianb1e7cd12013-02-14 17:11:27 -080041#include <gui/Surface.h>
Nicolas Catania1d187f12009-05-12 23:25:55 -070042#include <utils/Errors.h> // for status_t
43#include <utils/String8.h>
Marco Nelissen10dbb8e2009-09-20 10:42:13 -070044#include <utils/SystemClock.h>
Lajos Molnar06ad1522014-08-28 07:27:44 -070045#include <utils/Timers.h>
Nicolas Catania1d187f12009-05-12 23:25:55 -070046#include <utils/Vector.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080047
Eric Laurent43562692015-07-15 16:49:07 -070048#include <media/AudioPolicyHelper.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080049#include <media/IMediaHTTPService.h>
Jeff Brown2013a542012-09-04 21:38:42 -070050#include <media/IRemoteDisplay.h>
51#include <media/IRemoteDisplayClient.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080052#include <media/MediaPlayerInterface.h>
53#include <media/mediarecorder.h>
54#include <media/MediaMetadataRetrieverInterface.h>
nikoa64c8c72009-07-20 15:07:26 -070055#include <media/Metadata.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080056#include <media/AudioTrack.h>
James Dong8635b7b2011-03-14 17:01:38 -070057#include <media/MemoryLeakTrackUtil.h>
Lajos Molnar1381d4b2014-08-07 15:18:35 -070058#include <media/stagefright/MediaCodecList.h>
Eric Laurent9cb839a2011-09-27 09:48:56 -070059#include <media/stagefright/MediaErrors.h>
Marco Nelissen83b0fd92015-09-16 13:48:07 -070060#include <media/stagefright/Utils.h>
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +010061#include <media/stagefright/foundation/ADebug.h>
Marco Nelissenf09611f2015-02-13 14:12:42 -080062#include <media/stagefright/foundation/ALooperRoster.h>
Chong Zhang181fd9b2017-02-16 15:53:03 -080063#include <media/stagefright/SurfaceUtils.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070064#include <mediautils/BatteryNotifier.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080065
Andy Hung53541292016-04-13 16:48:51 -070066#include <memunreachable/memunreachable.h>
Dima Zavin64760242011-05-11 14:15:23 -070067#include <system/audio.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070068
Gloria Wang7cf180c2011-02-19 18:37:57 -080069#include <private/android_filesystem_config.h>
70
James Dong559bf282012-03-28 10:29:14 -070071#include "ActivityManager.h"
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080072#include "MediaRecorderClient.h"
73#include "MediaPlayerService.h"
74#include "MetadataRetrieverClient.h"
John Grossman44a7e422012-06-21 17:29:24 -070075#include "MediaPlayerFactory.h"
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080076
Nicolas Catania14d27472009-07-13 14:37:49 -070077#include "TestPlayerStub.h"
Andreas Huberf9334412010-12-15 15:17:42 -080078#include "nuplayer/NuPlayerDriver.h"
Andreas Huber20111aa2009-07-14 16:56:47 -070079
Andreas Huber20111aa2009-07-14 16:56:47 -070080#include <OMX.h>
Nicolas Catania14d27472009-07-13 14:37:49 -070081
Andreas Huber59451f82012-09-18 10:36:32 -070082#include "HDCP.h"
Andreas Huberb7319a72013-05-29 14:20:52 -070083#include "HTTPBase.h"
Andreas Huber35213f12012-08-29 11:41:50 -070084#include "RemoteDisplay.h"
Andreas Hubered3e3e02012-03-26 11:13:27 -070085
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070086namespace {
nikoa64c8c72009-07-20 15:07:26 -070087using android::media::Metadata;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070088using android::status_t;
89using android::OK;
90using android::BAD_VALUE;
91using android::NOT_ENOUGH_DATA;
92using android::Parcel;
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
Marco Nelissen260e56c2016-01-28 21:41:25 +0000337sp<IOMX> MediaPlayerService::getOMX() {
Marco Nelissen1900e772016-02-02 16:12:16 -0800338 ALOGI("MediaPlayerService::getOMX");
Marco Nelissen260e56c2016-01-28 21:41:25 +0000339 Mutex::Autolock autoLock(mLock);
340
341 if (mOMX.get() == NULL) {
342 mOMX = new OMX;
343 }
344
345 return mOMX;
346}
347
Andreas Huber279dcd82013-01-30 10:41:25 -0800348sp<IHDCP> MediaPlayerService::makeHDCP(bool createEncryptionModule) {
349 return new HDCP(createEncryptionModule);
Andreas Huber59451f82012-09-18 10:36:32 -0700350}
351
Jeff Brown2013a542012-09-04 21:38:42 -0700352sp<IRemoteDisplay> MediaPlayerService::listenForRemoteDisplay(
Svet Ganovbe71aa22015-04-28 12:06:02 -0700353 const String16 &opPackageName,
Jeff Brown2013a542012-09-04 21:38:42 -0700354 const sp<IRemoteDisplayClient>& client, const String8& iface) {
Jeff Brownaba33d52012-09-07 17:38:58 -0700355 if (!checkPermission("android.permission.CONTROL_WIFI_DISPLAY")) {
356 return NULL;
357 }
358
Svet Ganovbe71aa22015-04-28 12:06:02 -0700359 return new RemoteDisplay(opPackageName, client, iface.string());
Jeff Brown2013a542012-09-04 21:38:42 -0700360}
361
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800362status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
363{
364 const size_t SIZE = 256;
365 char buffer[SIZE];
366 String8 result;
367
368 result.append(" AudioOutput\n");
369 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n",
370 mStreamType, mLeftVolume, mRightVolume);
371 result.append(buffer);
372 snprintf(buffer, 255, " msec per frame(%f), latency (%d)\n",
Eric Laurentdb354e52012-03-05 17:27:11 -0800373 mMsecsPerFrame, (mTrack != 0) ? mTrack->latency() : -1);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800374 result.append(buffer);
Eric Laurent2beeb502010-07-16 07:43:46 -0700375 snprintf(buffer, 255, " aux effect id(%d), send level (%f)\n",
376 mAuxEffectId, mSendLevel);
377 result.append(buffer);
378
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800379 ::write(fd, result.string(), result.size());
380 if (mTrack != 0) {
381 mTrack->dump(fd, args);
382 }
383 return NO_ERROR;
384}
385
Lajos Molnar6d339f12015-04-17 16:15:53 -0700386status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800387{
388 const size_t SIZE = 256;
389 char buffer[SIZE];
390 String8 result;
391 result.append(" Client\n");
392 snprintf(buffer, 255, " pid(%d), connId(%d), status(%d), looping(%s)\n",
393 mPid, mConnId, mStatus, mLoop?"true": "false");
394 result.append(buffer);
395 write(fd, result.string(), result.size());
Andreas Hubera0b1d4b2011-06-07 15:52:25 -0700396 if (mPlayer != NULL) {
397 mPlayer->dump(fd, args);
398 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800399 if (mAudioOutput != 0) {
400 mAudioOutput->dump(fd, args);
401 }
402 write(fd, "\n", 1);
403 return NO_ERROR;
404}
405
Marco Nelissenf09611f2015-02-13 14:12:42 -0800406/**
407 * The only arguments this understands right now are -c, -von and -voff,
408 * which are parsed by ALooperRoster::dump()
409 */
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800410status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
411{
412 const size_t SIZE = 256;
413 char buffer[SIZE];
414 String8 result;
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530415 SortedVector< sp<Client> > clients; //to serialise the mutex unlock & client destruction.
416 SortedVector< sp<MediaRecorderClient> > mediaRecorderClients;
417
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800418 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
419 snprintf(buffer, SIZE, "Permission Denial: "
420 "can't dump MediaPlayerService from pid=%d, uid=%d\n",
421 IPCThreadState::self()->getCallingPid(),
422 IPCThreadState::self()->getCallingUid());
423 result.append(buffer);
424 } else {
425 Mutex::Autolock lock(mLock);
426 for (int i = 0, n = mClients.size(); i < n; ++i) {
427 sp<Client> c = mClients[i].promote();
428 if (c != 0) c->dump(fd, args);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530429 clients.add(c);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800430 }
James Dongb9141222010-07-08 11:16:11 -0700431 if (mMediaRecorderClients.size() == 0) {
432 result.append(" No media recorder client\n\n");
433 } else {
434 for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
435 sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
James Donge579e282011-10-18 22:29:20 -0700436 if (c != 0) {
437 snprintf(buffer, 255, " MediaRecorderClient pid(%d)\n", c->mPid);
438 result.append(buffer);
439 write(fd, result.string(), result.size());
440 result = "\n";
441 c->dump(fd, args);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530442 mediaRecorderClients.add(c);
James Donge579e282011-10-18 22:29:20 -0700443 }
James Dongb9141222010-07-08 11:16:11 -0700444 }
Gloria Wangdac6a312009-10-29 15:46:37 -0700445 }
446
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800447 result.append(" Files opened and/or mapped:\n");
Marco Nelissenf09611f2015-02-13 14:12:42 -0800448 snprintf(buffer, SIZE, "/proc/%d/maps", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800449 FILE *f = fopen(buffer, "r");
450 if (f) {
451 while (!feof(f)) {
452 fgets(buffer, SIZE, f);
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700453 if (strstr(buffer, " /storage/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800454 strstr(buffer, " /system/sounds/") ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700455 strstr(buffer, " /data/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800456 strstr(buffer, " /system/media/")) {
457 result.append(" ");
458 result.append(buffer);
459 }
460 }
461 fclose(f);
462 } else {
463 result.append("couldn't open ");
464 result.append(buffer);
465 result.append("\n");
466 }
467
Marco Nelissenf09611f2015-02-13 14:12:42 -0800468 snprintf(buffer, SIZE, "/proc/%d/fd", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800469 DIR *d = opendir(buffer);
470 if (d) {
471 struct dirent *ent;
472 while((ent = readdir(d)) != NULL) {
473 if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
Marco Nelissenf09611f2015-02-13 14:12:42 -0800474 snprintf(buffer, SIZE, "/proc/%d/fd/%s", getpid(), ent->d_name);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800475 struct stat s;
476 if (lstat(buffer, &s) == 0) {
477 if ((s.st_mode & S_IFMT) == S_IFLNK) {
478 char linkto[256];
479 int len = readlink(buffer, linkto, sizeof(linkto));
480 if(len > 0) {
481 if(len > 255) {
482 linkto[252] = '.';
483 linkto[253] = '.';
484 linkto[254] = '.';
485 linkto[255] = 0;
486 } else {
487 linkto[len] = 0;
488 }
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700489 if (strstr(linkto, "/storage/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800490 strstr(linkto, "/system/sounds/") == linkto ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700491 strstr(linkto, "/data/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800492 strstr(linkto, "/system/media/") == linkto) {
493 result.append(" ");
494 result.append(buffer);
495 result.append(" -> ");
496 result.append(linkto);
497 result.append("\n");
498 }
499 }
500 } else {
501 result.append(" unexpected type for ");
502 result.append(buffer);
503 result.append("\n");
504 }
505 }
506 }
507 }
508 closedir(d);
509 } else {
510 result.append("couldn't open ");
511 result.append(buffer);
512 result.append("\n");
513 }
514
Marco Nelissenf09611f2015-02-13 14:12:42 -0800515 gLooperRoster.dump(fd, args);
516
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800517 bool dumpMem = false;
Andy Hung53541292016-04-13 16:48:51 -0700518 bool unreachableMemory = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800519 for (size_t i = 0; i < args.size(); i++) {
520 if (args[i] == String16("-m")) {
521 dumpMem = true;
Andy Hung53541292016-04-13 16:48:51 -0700522 } else if (args[i] == String16("--unreachable")) {
523 unreachableMemory = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800524 }
525 }
526 if (dumpMem) {
Andy Hung07b745e2016-05-23 16:21:07 -0700527 result.append("\nDumping memory:\n");
528 std::string s = dumpMemoryAddresses(100 /* limit */);
529 result.append(s.c_str(), s.size());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800530 }
Andy Hung53541292016-04-13 16:48:51 -0700531 if (unreachableMemory) {
532 result.append("\nDumping unreachable memory:\n");
533 // TODO - should limit be an argument parameter?
534 std::string s = GetUnreachableMemoryString(true /* contents */, 10000 /* limit */);
535 result.append(s.c_str(), s.size());
536 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800537 }
538 write(fd, result.string(), result.size());
539 return NO_ERROR;
540}
541
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -0700542void MediaPlayerService::removeClient(const wp<Client>& client)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800543{
544 Mutex::Autolock lock(mLock);
545 mClients.remove(client);
546}
547
Robert Shihee0a0e32016-08-16 16:50:54 -0700548bool MediaPlayerService::hasClient(wp<Client> client)
549{
550 Mutex::Autolock lock(mLock);
551 return mClients.indexOf(client) != NAME_NOT_FOUND;
552}
553
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700554MediaPlayerService::Client::Client(
555 const sp<MediaPlayerService>& service, pid_t pid,
556 int32_t connId, const sp<IMediaPlayerClient>& client,
Glenn Kastend848eb42016-03-08 13:42:11 -0800557 audio_session_t audioSessionId, uid_t uid)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800558{
Steve Block3856b092011-10-20 11:56:00 +0100559 ALOGV("Client(%d) constructor", connId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800560 mPid = pid;
561 mConnId = connId;
562 mService = service;
563 mClient = client;
564 mLoop = false;
565 mStatus = NO_INIT;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700566 mAudioSessionId = audioSessionId;
Andy Hung1afd0982016-11-08 16:13:44 -0800567 mUid = uid;
John Grossmanc795b642012-02-22 15:38:35 -0800568 mRetransmitEndpointValid = false;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700569 mAudioAttributes = NULL;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700570
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800571#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000572 ALOGD("create Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800573 mAntagonizer = new Antagonizer(notify, this);
574#endif
575}
576
577MediaPlayerService::Client::~Client()
578{
Steve Block3856b092011-10-20 11:56:00 +0100579 ALOGV("Client(%d) destructor pid = %d", mConnId, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800580 mAudioOutput.clear();
581 wp<Client> client(this);
582 disconnect();
583 mService->removeClient(client);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700584 if (mAudioAttributes != NULL) {
585 free(mAudioAttributes);
586 }
Pawin Vongmasa9c47c972017-02-08 04:09:38 -0800587 clearDeathNotifiers();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800588}
589
590void MediaPlayerService::Client::disconnect()
591{
Steve Block3856b092011-10-20 11:56:00 +0100592 ALOGV("disconnect(%d) from pid %d", mConnId, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800593 // grab local reference and clear main reference to prevent future
594 // access to object
595 sp<MediaPlayerBase> p;
596 {
597 Mutex::Autolock l(mLock);
598 p = mPlayer;
beanzdcfefde2012-11-05 09:51:43 +0800599 mClient.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800600 }
Andreas Huber20111aa2009-07-14 16:56:47 -0700601
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800602 mPlayer.clear();
603
604 // clear the notification to prevent callbacks to dead client
605 // and reset the player. We assume the player will serialize
606 // access to itself if necessary.
607 if (p != 0) {
608 p->setNotifyCallback(0, 0);
609#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000610 ALOGD("kill Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800611 mAntagonizer->kill();
612#endif
613 p->reset();
614 }
615
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700616 disconnectNativeWindow();
617
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800618 IPCThreadState::self()->flushCommands();
619}
620
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800621sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
622{
623 // determine if we have the right player type
624 sp<MediaPlayerBase> p = mPlayer;
625 if ((p != NULL) && (p->playerType() != playerType)) {
Steve Block3856b092011-10-20 11:56:00 +0100626 ALOGV("delete player");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800627 p.clear();
628 }
629 if (p == NULL) {
Ronghua Wu68845c12015-07-21 09:50:48 -0700630 p = MediaPlayerFactory::createPlayer(playerType, this, notify, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800631 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700632
Jason Simmonsdb29e522011-08-12 13:46:55 -0700633 if (p != NULL) {
Andy Hung1afd0982016-11-08 16:13:44 -0800634 p->setUID(mUid);
Jason Simmonsdb29e522011-08-12 13:46:55 -0700635 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700636
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800637 return p;
638}
639
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700640MediaPlayerService::Client::ServiceDeathNotifier::ServiceDeathNotifier(
641 const sp<IBinder>& service,
642 const sp<MediaPlayerBase>& listener,
643 int which) {
644 mService = service;
Pawin Vongmasa9c47c972017-02-08 04:09:38 -0800645 mOmx = nullptr;
646 mListener = listener;
647 mWhich = which;
648}
649
650MediaPlayerService::Client::ServiceDeathNotifier::ServiceDeathNotifier(
651 const sp<IOmx>& omx,
652 const sp<MediaPlayerBase>& listener,
653 int which) {
654 mService = nullptr;
655 mOmx = omx;
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700656 mListener = listener;
657 mWhich = which;
658}
659
660MediaPlayerService::Client::ServiceDeathNotifier::~ServiceDeathNotifier() {
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700661}
662
663void MediaPlayerService::Client::ServiceDeathNotifier::binderDied(const wp<IBinder>& /*who*/) {
664 sp<MediaPlayerBase> listener = mListener.promote();
665 if (listener != NULL) {
666 listener->sendEvent(MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED, mWhich);
667 } else {
668 ALOGW("listener for process %d death is gone", mWhich);
669 }
670}
671
Pawin Vongmasa9c47c972017-02-08 04:09:38 -0800672void MediaPlayerService::Client::ServiceDeathNotifier::serviceDied(
673 uint64_t /* cookie */,
674 const wp<::android::hidl::base::V1_0::IBase>& /* who */) {
675 sp<MediaPlayerBase> listener = mListener.promote();
676 if (listener != NULL) {
677 listener->sendEvent(MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED, mWhich);
678 } else {
679 ALOGW("listener for process %d death is gone", mWhich);
680 }
681}
682
683void MediaPlayerService::Client::ServiceDeathNotifier::unlinkToDeath() {
684 if (mService != nullptr) {
685 mService->unlinkToDeath(this);
686 mService = nullptr;
687 } else if (mOmx != nullptr) {
688 mOmx->unlinkToDeath(this);
689 mOmx = nullptr;
690 }
691}
692
693void MediaPlayerService::Client::clearDeathNotifiers() {
694 if (mExtractorDeathListener != nullptr) {
695 mExtractorDeathListener->unlinkToDeath();
696 mExtractorDeathListener = nullptr;
697 }
698 if (mCodecDeathListener != nullptr) {
699 mCodecDeathListener->unlinkToDeath();
700 mCodecDeathListener = nullptr;
701 }
702}
703
John Grossmanc795b642012-02-22 15:38:35 -0800704sp<MediaPlayerBase> MediaPlayerService::Client::setDataSource_pre(
705 player_type playerType)
706{
707 ALOGV("player type = %d", playerType);
Pawin Vongmasa9c47c972017-02-08 04:09:38 -0800708 clearDeathNotifiers();
John Grossmanc795b642012-02-22 15:38:35 -0800709
710 // create the right type of player
711 sp<MediaPlayerBase> p = createPlayer(playerType);
712 if (p == NULL) {
713 return p;
714 }
715
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700716 sp<IServiceManager> sm = defaultServiceManager();
717 sp<IBinder> binder = sm->getService(String16("media.extractor"));
Marco Nelissen1b5a7ee2016-09-30 13:54:30 -0700718 if (binder == NULL) {
719 ALOGE("extractor service not available");
720 return NULL;
721 }
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700722 mExtractorDeathListener = new ServiceDeathNotifier(binder, p, MEDIAEXTRACTOR_PROCESS_DEATH);
723 binder->linkToDeath(mExtractorDeathListener);
724
Pawin Vongmasad4e9ca42017-03-29 17:24:56 -0700725 if (property_get_bool("persist.media.treble_omx", true)) {
Pawin Vongmasa9c47c972017-02-08 04:09:38 -0800726 // Treble IOmx
727 sp<IOmx> omx = IOmx::getService();
728 if (omx == nullptr) {
729 ALOGE("Treble IOmx not available");
730 return NULL;
731 }
732 mCodecDeathListener = new ServiceDeathNotifier(omx, p, MEDIACODEC_PROCESS_DEATH);
733 omx->linkToDeath(mCodecDeathListener, 0);
734 } else {
735 // Legacy IOMX
736 binder = sm->getService(String16("media.codec"));
737 if (binder == NULL) {
738 ALOGE("codec service not available");
739 return NULL;
740 }
741 mCodecDeathListener = new ServiceDeathNotifier(binder, p, MEDIACODEC_PROCESS_DEATH);
742 binder->linkToDeath(mCodecDeathListener);
Marco Nelissen1b5a7ee2016-09-30 13:54:30 -0700743 }
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700744
John Grossmanc795b642012-02-22 15:38:35 -0800745 if (!p->hardwareOutput()) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -0700746 Mutex::Autolock l(mLock);
Marco Nelissend457c972014-02-11 08:47:07 -0800747 mAudioOutput = new AudioOutput(mAudioSessionId, IPCThreadState::self()->getCallingUid(),
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700748 mPid, mAudioAttributes);
John Grossmanc795b642012-02-22 15:38:35 -0800749 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
750 }
751
752 return p;
753}
754
755void MediaPlayerService::Client::setDataSource_post(
756 const sp<MediaPlayerBase>& p,
757 status_t status)
758{
759 ALOGV(" setDataSource");
760 mStatus = status;
761 if (mStatus != OK) {
762 ALOGE(" error: %d", mStatus);
763 return;
764 }
765
766 // Set the re-transmission endpoint if one was chosen.
767 if (mRetransmitEndpointValid) {
768 mStatus = p->setRetransmitEndpoint(&mRetransmitEndpoint);
769 if (mStatus != NO_ERROR) {
770 ALOGE("setRetransmitEndpoint error: %d", mStatus);
771 }
772 }
773
774 if (mStatus == OK) {
775 mPlayer = p;
776 }
777}
778
Andreas Huber2db84552010-01-28 11:19:57 -0800779status_t MediaPlayerService::Client::setDataSource(
Andreas Huber1b86fe02014-01-29 11:13:26 -0800780 const sp<IMediaHTTPService> &httpService,
781 const char *url,
782 const KeyedVector<String8, String8> *headers)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800783{
Steve Block3856b092011-10-20 11:56:00 +0100784 ALOGV("setDataSource(%s)", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800785 if (url == NULL)
786 return UNKNOWN_ERROR;
787
Dave Burked681bbb2011-08-30 14:39:17 +0100788 if ((strncmp(url, "http://", 7) == 0) ||
789 (strncmp(url, "https://", 8) == 0) ||
790 (strncmp(url, "rtsp://", 7) == 0)) {
791 if (!checkPermission("android.permission.INTERNET")) {
792 return PERMISSION_DENIED;
793 }
794 }
795
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800796 if (strncmp(url, "content://", 10) == 0) {
797 // get a filedescriptor for the content Uri and
798 // pass it to the setDataSource(fd) method
799
800 String16 url16(url);
801 int fd = android::openContentProviderFile(url16);
802 if (fd < 0)
803 {
Steve Block29357bc2012-01-06 19:20:56 +0000804 ALOGE("Couldn't open fd for %s", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800805 return UNKNOWN_ERROR;
806 }
807 setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
808 close(fd);
809 return mStatus;
810 } else {
John Grossman44a7e422012-06-21 17:29:24 -0700811 player_type playerType = MediaPlayerFactory::getPlayerType(this, url);
John Grossmanc795b642012-02-22 15:38:35 -0800812 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
813 if (p == NULL) {
814 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800815 }
816
Andreas Huber1b86fe02014-01-29 11:13:26 -0800817 setDataSource_post(p, p->setDataSource(httpService, url, headers));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800818 return mStatus;
819 }
820}
821
822status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
823{
Marco Nelissen83b0fd92015-09-16 13:48:07 -0700824 ALOGV("setDataSource fd=%d (%s), offset=%lld, length=%lld",
825 fd, nameForFd(fd).c_str(), (long long) offset, (long long) length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800826 struct stat sb;
827 int ret = fstat(fd, &sb);
828 if (ret != 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000829 ALOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800830 return UNKNOWN_ERROR;
831 }
832
Andy Hung833b4752016-04-04 17:15:48 -0700833 ALOGV("st_dev = %llu", static_cast<unsigned long long>(sb.st_dev));
Steve Block3856b092011-10-20 11:56:00 +0100834 ALOGV("st_mode = %u", sb.st_mode);
Mark Salyzyn77342f72014-06-18 16:31:32 -0700835 ALOGV("st_uid = %lu", static_cast<unsigned long>(sb.st_uid));
836 ALOGV("st_gid = %lu", static_cast<unsigned long>(sb.st_gid));
Andy Hung833b4752016-04-04 17:15:48 -0700837 ALOGV("st_size = %llu", static_cast<unsigned long long>(sb.st_size));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800838
839 if (offset >= sb.st_size) {
Steve Block29357bc2012-01-06 19:20:56 +0000840 ALOGE("offset error");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800841 return UNKNOWN_ERROR;
842 }
843 if (offset + length > sb.st_size) {
844 length = sb.st_size - offset;
Andy Hung833b4752016-04-04 17:15:48 -0700845 ALOGV("calculated length = %lld", (long long)length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800846 }
847
John Grossman44a7e422012-06-21 17:29:24 -0700848 player_type playerType = MediaPlayerFactory::getPlayerType(this,
849 fd,
850 offset,
851 length);
John Grossmanc795b642012-02-22 15:38:35 -0800852 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
853 if (p == NULL) {
854 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800855 }
856
857 // now set data source
John Grossmanc795b642012-02-22 15:38:35 -0800858 setDataSource_post(p, p->setDataSource(fd, offset, length));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800859 return mStatus;
860}
861
Andreas Hubere2b10282010-11-23 11:41:34 -0800862status_t MediaPlayerService::Client::setDataSource(
863 const sp<IStreamSource> &source) {
864 // create the right type of player
John Grossman44a7e422012-06-21 17:29:24 -0700865 player_type playerType = MediaPlayerFactory::getPlayerType(this, source);
John Grossmanc795b642012-02-22 15:38:35 -0800866 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
Andreas Hubere2b10282010-11-23 11:41:34 -0800867 if (p == NULL) {
868 return NO_INIT;
869 }
870
Andreas Hubere2b10282010-11-23 11:41:34 -0800871 // now set data source
John Grossmanc795b642012-02-22 15:38:35 -0800872 setDataSource_post(p, p->setDataSource(source));
Andreas Hubere2b10282010-11-23 11:41:34 -0800873 return mStatus;
874}
875
Chris Watkins99f31602015-03-20 13:06:33 -0700876status_t MediaPlayerService::Client::setDataSource(
877 const sp<IDataSource> &source) {
878 sp<DataSource> dataSource = DataSource::CreateFromIDataSource(source);
879 player_type playerType = MediaPlayerFactory::getPlayerType(this, dataSource);
880 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
881 if (p == NULL) {
882 return NO_INIT;
883 }
884 // now set data source
885 setDataSource_post(p, p->setDataSource(dataSource));
886 return mStatus;
887}
888
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700889void MediaPlayerService::Client::disconnectNativeWindow() {
890 if (mConnectedWindow != NULL) {
Chong Zhang181fd9b2017-02-16 15:53:03 -0800891 status_t err = nativeWindowDisconnect(
892 mConnectedWindow.get(), "disconnectNativeWindow");
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700893
894 if (err != OK) {
Chong Zhang181fd9b2017-02-16 15:53:03 -0800895 ALOGW("nativeWindowDisconnect returned an error: %s (%d)",
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700896 strerror(-err), err);
897 }
898 }
899 mConnectedWindow.clear();
900}
901
Glenn Kasten11731182011-02-08 17:26:17 -0800902status_t MediaPlayerService::Client::setVideoSurfaceTexture(
Andy McFadden484566c2012-12-18 09:46:54 -0800903 const sp<IGraphicBufferProducer>& bufferProducer)
Glenn Kasten11731182011-02-08 17:26:17 -0800904{
Andy McFadden484566c2012-12-18 09:46:54 -0800905 ALOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, bufferProducer.get());
Glenn Kasten11731182011-02-08 17:26:17 -0800906 sp<MediaPlayerBase> p = getPlayer();
907 if (p == 0) return UNKNOWN_ERROR;
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700908
Marco Nelissenf8880202014-11-14 07:58:25 -0800909 sp<IBinder> binder(IInterface::asBinder(bufferProducer));
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700910 if (mConnectedWindowBinder == binder) {
911 return OK;
912 }
913
914 sp<ANativeWindow> anw;
Andy McFadden484566c2012-12-18 09:46:54 -0800915 if (bufferProducer != NULL) {
Marco Nelissenee08f7e2013-09-16 13:30:01 -0700916 anw = new Surface(bufferProducer, true /* controlledByApp */);
Chong Zhang181fd9b2017-02-16 15:53:03 -0800917 status_t err = nativeWindowConnect(anw.get(), "setVideoSurfaceTexture");
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700918
919 if (err != OK) {
Steve Block29357bc2012-01-06 19:20:56 +0000920 ALOGE("setVideoSurfaceTexture failed: %d", err);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700921 // Note that we must do the reset before disconnecting from the ANW.
922 // Otherwise queue/dequeue calls could be made on the disconnected
923 // ANW, which may result in errors.
924 reset();
925
926 disconnectNativeWindow();
927
928 return err;
929 }
930 }
931
Andy McFadden484566c2012-12-18 09:46:54 -0800932 // Note that we must set the player's new GraphicBufferProducer before
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700933 // disconnecting the old one. Otherwise queue/dequeue calls could be made
934 // on the disconnected ANW, which may result in errors.
Andy McFadden484566c2012-12-18 09:46:54 -0800935 status_t err = p->setVideoSurfaceTexture(bufferProducer);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700936
937 disconnectNativeWindow();
938
939 mConnectedWindow = anw;
940
941 if (err == OK) {
942 mConnectedWindowBinder = binder;
943 } else {
944 disconnectNativeWindow();
945 }
946
947 return err;
Glenn Kasten11731182011-02-08 17:26:17 -0800948}
949
Nicolas Catania1d187f12009-05-12 23:25:55 -0700950status_t MediaPlayerService::Client::invoke(const Parcel& request,
951 Parcel *reply)
952{
953 sp<MediaPlayerBase> p = getPlayer();
954 if (p == NULL) return UNKNOWN_ERROR;
955 return p->invoke(request, reply);
956}
957
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700958// This call doesn't need to access the native player.
959status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
960{
961 status_t status;
nikoa64c8c72009-07-20 15:07:26 -0700962 media::Metadata::Filter allow, drop;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700963
Nicolas Catania48290382009-07-10 13:53:06 -0700964 if (unmarshallFilter(filter, &allow, &status) &&
965 unmarshallFilter(filter, &drop, &status)) {
966 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700967
968 mMetadataAllow = allow;
969 mMetadataDrop = drop;
970 }
971 return status;
972}
973
Nicolas Catania48290382009-07-10 13:53:06 -0700974status_t MediaPlayerService::Client::getMetadata(
Mark Salyzyn77342f72014-06-18 16:31:32 -0700975 bool update_only, bool /*apply_filter*/, Parcel *reply)
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700976{
nikoa64c8c72009-07-20 15:07:26 -0700977 sp<MediaPlayerBase> player = getPlayer();
978 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania48290382009-07-10 13:53:06 -0700979
nikod608a812009-07-16 16:39:53 -0700980 status_t status;
981 // Placeholder for the return code, updated by the caller.
982 reply->writeInt32(-1);
983
nikoa64c8c72009-07-20 15:07:26 -0700984 media::Metadata::Filter ids;
Nicolas Catania48290382009-07-10 13:53:06 -0700985
986 // We don't block notifications while we fetch the data. We clear
987 // mMetadataUpdated first so we don't lose notifications happening
988 // during the rest of this call.
989 {
990 Mutex::Autolock lock(mLock);
991 if (update_only) {
nikod608a812009-07-16 16:39:53 -0700992 ids = mMetadataUpdated;
Nicolas Catania48290382009-07-10 13:53:06 -0700993 }
994 mMetadataUpdated.clear();
995 }
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700996
nikoa64c8c72009-07-20 15:07:26 -0700997 media::Metadata metadata(reply);
Nicolas Catania48290382009-07-10 13:53:06 -0700998
nikoa64c8c72009-07-20 15:07:26 -0700999 metadata.appendHeader();
1000 status = player->getMetadata(ids, reply);
nikod608a812009-07-16 16:39:53 -07001001
1002 if (status != OK) {
nikoa64c8c72009-07-20 15:07:26 -07001003 metadata.resetParcel();
Steve Block29357bc2012-01-06 19:20:56 +00001004 ALOGE("getMetadata failed %d", status);
nikod608a812009-07-16 16:39:53 -07001005 return status;
1006 }
1007
1008 // FIXME: Implement filtering on the result. Not critical since
1009 // filtering takes place on the update notifications already. This
1010 // would be when all the metadata are fetch and a filter is set.
1011
nikod608a812009-07-16 16:39:53 -07001012 // Everything is fine, update the metadata length.
nikoa64c8c72009-07-20 15:07:26 -07001013 metadata.updateLength();
nikod608a812009-07-16 16:39:53 -07001014 return OK;
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001015}
1016
Wei Jiad399e7e2016-10-26 15:49:11 -07001017status_t MediaPlayerService::Client::setBufferingSettings(
1018 const BufferingSettings& buffering)
1019{
Wei Jiadc6f3402017-01-09 15:04:18 -08001020 ALOGV("[%d] setBufferingSettings{%s}",
1021 mConnId, buffering.toString().string());
Wei Jiad399e7e2016-10-26 15:49:11 -07001022 sp<MediaPlayerBase> p = getPlayer();
1023 if (p == 0) return UNKNOWN_ERROR;
1024 return p->setBufferingSettings(buffering);
1025}
1026
1027status_t MediaPlayerService::Client::getDefaultBufferingSettings(
1028 BufferingSettings* buffering /* nonnull */)
1029{
1030 sp<MediaPlayerBase> p = getPlayer();
1031 // TODO: create mPlayer on demand.
1032 if (p == 0) return UNKNOWN_ERROR;
1033 status_t ret = p->getDefaultBufferingSettings(buffering);
1034 if (ret == NO_ERROR) {
Wei Jiadc6f3402017-01-09 15:04:18 -08001035 ALOGV("[%d] getDefaultBufferingSettings{%s}",
1036 mConnId, buffering->toString().string());
Wei Jiad399e7e2016-10-26 15:49:11 -07001037 } else {
1038 ALOGV("[%d] getDefaultBufferingSettings returned %d", mConnId, ret);
1039 }
1040 return ret;
1041}
1042
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001043status_t MediaPlayerService::Client::prepareAsync()
1044{
Steve Block3856b092011-10-20 11:56:00 +01001045 ALOGV("[%d] prepareAsync", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001046 sp<MediaPlayerBase> p = getPlayer();
1047 if (p == 0) return UNKNOWN_ERROR;
1048 status_t ret = p->prepareAsync();
1049#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +00001050 ALOGD("start Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001051 if (ret == NO_ERROR) mAntagonizer->start();
1052#endif
1053 return ret;
1054}
1055
1056status_t MediaPlayerService::Client::start()
1057{
Steve Block3856b092011-10-20 11:56:00 +01001058 ALOGV("[%d] start", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001059 sp<MediaPlayerBase> p = getPlayer();
1060 if (p == 0) return UNKNOWN_ERROR;
1061 p->setLooping(mLoop);
1062 return p->start();
1063}
1064
1065status_t MediaPlayerService::Client::stop()
1066{
Steve Block3856b092011-10-20 11:56:00 +01001067 ALOGV("[%d] stop", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001068 sp<MediaPlayerBase> p = getPlayer();
1069 if (p == 0) return UNKNOWN_ERROR;
1070 return p->stop();
1071}
1072
1073status_t MediaPlayerService::Client::pause()
1074{
Steve Block3856b092011-10-20 11:56:00 +01001075 ALOGV("[%d] pause", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001076 sp<MediaPlayerBase> p = getPlayer();
1077 if (p == 0) return UNKNOWN_ERROR;
1078 return p->pause();
1079}
1080
1081status_t MediaPlayerService::Client::isPlaying(bool* state)
1082{
1083 *state = false;
1084 sp<MediaPlayerBase> p = getPlayer();
1085 if (p == 0) return UNKNOWN_ERROR;
1086 *state = p->isPlaying();
Steve Block3856b092011-10-20 11:56:00 +01001087 ALOGV("[%d] isPlaying: %d", mConnId, *state);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001088 return NO_ERROR;
1089}
1090
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001091status_t MediaPlayerService::Client::setPlaybackSettings(const AudioPlaybackRate& rate)
Wei Jia98160162015-02-04 17:01:11 -08001092{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001093 ALOGV("[%d] setPlaybackSettings(%f, %f, %d, %d)",
1094 mConnId, rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Wei Jia98160162015-02-04 17:01:11 -08001095 sp<MediaPlayerBase> p = getPlayer();
1096 if (p == 0) return UNKNOWN_ERROR;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001097 return p->setPlaybackSettings(rate);
1098}
1099
1100status_t MediaPlayerService::Client::getPlaybackSettings(AudioPlaybackRate* rate /* nonnull */)
1101{
1102 sp<MediaPlayerBase> p = getPlayer();
1103 if (p == 0) return UNKNOWN_ERROR;
1104 status_t ret = p->getPlaybackSettings(rate);
1105 if (ret == NO_ERROR) {
1106 ALOGV("[%d] getPlaybackSettings(%f, %f, %d, %d)",
1107 mConnId, rate->mSpeed, rate->mPitch, rate->mFallbackMode, rate->mStretchMode);
1108 } else {
1109 ALOGV("[%d] getPlaybackSettings returned %d", mConnId, ret);
1110 }
1111 return ret;
1112}
1113
1114status_t MediaPlayerService::Client::setSyncSettings(
1115 const AVSyncSettings& sync, float videoFpsHint)
1116{
1117 ALOGV("[%d] setSyncSettings(%u, %u, %f, %f)",
1118 mConnId, sync.mSource, sync.mAudioAdjustMode, sync.mTolerance, videoFpsHint);
1119 sp<MediaPlayerBase> p = getPlayer();
1120 if (p == 0) return UNKNOWN_ERROR;
1121 return p->setSyncSettings(sync, videoFpsHint);
1122}
1123
1124status_t MediaPlayerService::Client::getSyncSettings(
1125 AVSyncSettings* sync /* nonnull */, float* videoFps /* nonnull */)
1126{
1127 sp<MediaPlayerBase> p = getPlayer();
1128 if (p == 0) return UNKNOWN_ERROR;
1129 status_t ret = p->getSyncSettings(sync, videoFps);
1130 if (ret == NO_ERROR) {
1131 ALOGV("[%d] getSyncSettings(%u, %u, %f, %f)",
1132 mConnId, sync->mSource, sync->mAudioAdjustMode, sync->mTolerance, *videoFps);
1133 } else {
1134 ALOGV("[%d] getSyncSettings returned %d", mConnId, ret);
1135 }
1136 return ret;
Wei Jia98160162015-02-04 17:01:11 -08001137}
1138
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001139status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
1140{
Steve Block3856b092011-10-20 11:56:00 +01001141 ALOGV("getCurrentPosition");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001142 sp<MediaPlayerBase> p = getPlayer();
1143 if (p == 0) return UNKNOWN_ERROR;
1144 status_t ret = p->getCurrentPosition(msec);
1145 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001146 ALOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001147 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001148 ALOGE("getCurrentPosition returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001149 }
1150 return ret;
1151}
1152
1153status_t MediaPlayerService::Client::getDuration(int *msec)
1154{
Steve Block3856b092011-10-20 11:56:00 +01001155 ALOGV("getDuration");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001156 sp<MediaPlayerBase> p = getPlayer();
1157 if (p == 0) return UNKNOWN_ERROR;
1158 status_t ret = p->getDuration(msec);
1159 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001160 ALOGV("[%d] getDuration = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001161 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001162 ALOGE("getDuration returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001163 }
1164 return ret;
1165}
1166
Marco Nelissen6b74d672012-02-28 16:07:44 -08001167status_t MediaPlayerService::Client::setNextPlayer(const sp<IMediaPlayer>& player) {
1168 ALOGV("setNextPlayer");
1169 Mutex::Autolock l(mLock);
1170 sp<Client> c = static_cast<Client*>(player.get());
Wei Jia28284122016-08-30 13:49:06 -07001171 if (c != NULL && !mService->hasClient(c)) {
Robert Shihee0a0e32016-08-16 16:50:54 -07001172 return BAD_VALUE;
1173 }
1174
Marco Nelissen6b74d672012-02-28 16:07:44 -08001175 mNextClient = c;
John Grossman5f7e55e2012-08-24 14:47:25 -07001176
1177 if (c != NULL) {
1178 if (mAudioOutput != NULL) {
1179 mAudioOutput->setNextOutput(c->mAudioOutput);
1180 } else if ((mPlayer != NULL) && !mPlayer->hardwareOutput()) {
1181 ALOGE("no current audio output");
1182 }
1183
1184 if ((mPlayer != NULL) && (mNextClient->getPlayer() != NULL)) {
1185 mPlayer->setNextPlayer(mNextClient->getPlayer());
1186 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001187 }
John Grossman5f7e55e2012-08-24 14:47:25 -07001188
Marco Nelissen6b74d672012-02-28 16:07:44 -08001189 return OK;
1190}
1191
Andy Hung9fc8b5c2017-01-24 13:36:48 -08001192VolumeShaper::Status MediaPlayerService::Client::applyVolumeShaper(
1193 const sp<VolumeShaper::Configuration>& configuration,
1194 const sp<VolumeShaper::Operation>& operation) {
1195 // for hardware output, call player instead
1196 ALOGV("Client::applyVolumeShaper(%p)", this);
1197 sp<MediaPlayerBase> p = getPlayer();
1198 {
1199 Mutex::Autolock l(mLock);
1200 if (p != 0 && p->hardwareOutput()) {
1201 // TODO: investigate internal implementation
1202 return VolumeShaper::Status(INVALID_OPERATION);
1203 }
1204 if (mAudioOutput.get() != nullptr) {
1205 return mAudioOutput->applyVolumeShaper(configuration, operation);
1206 }
1207 }
1208 return VolumeShaper::Status(INVALID_OPERATION);
1209}
1210
1211sp<VolumeShaper::State> MediaPlayerService::Client::getVolumeShaperState(int id) {
1212 // for hardware output, call player instead
1213 ALOGV("Client::getVolumeShaperState(%p)", this);
1214 sp<MediaPlayerBase> p = getPlayer();
1215 {
1216 Mutex::Autolock l(mLock);
1217 if (p != 0 && p->hardwareOutput()) {
1218 // TODO: investigate internal implementation.
1219 return nullptr;
1220 }
1221 if (mAudioOutput.get() != nullptr) {
1222 return mAudioOutput->getVolumeShaperState(id);
1223 }
1224 }
1225 return nullptr;
1226}
1227
Wei Jiac5de0912016-11-18 10:22:14 -08001228status_t MediaPlayerService::Client::seekTo(int msec, MediaPlayerSeekMode mode)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001229{
Wei Jiac5de0912016-11-18 10:22:14 -08001230 ALOGV("[%d] seekTo(%d, %d)", mConnId, msec, mode);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001231 sp<MediaPlayerBase> p = getPlayer();
1232 if (p == 0) return UNKNOWN_ERROR;
Wei Jiac5de0912016-11-18 10:22:14 -08001233 return p->seekTo(msec, mode);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001234}
1235
1236status_t MediaPlayerService::Client::reset()
1237{
Steve Block3856b092011-10-20 11:56:00 +01001238 ALOGV("[%d] reset", mConnId);
John Grossmanc795b642012-02-22 15:38:35 -08001239 mRetransmitEndpointValid = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001240 sp<MediaPlayerBase> p = getPlayer();
1241 if (p == 0) return UNKNOWN_ERROR;
1242 return p->reset();
1243}
1244
Glenn Kastenfff6d712012-01-12 16:38:12 -08001245status_t MediaPlayerService::Client::setAudioStreamType(audio_stream_type_t type)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001246{
Steve Block3856b092011-10-20 11:56:00 +01001247 ALOGV("[%d] setAudioStreamType(%d)", mConnId, type);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001248 // TODO: for hardware output, call player instead
1249 Mutex::Autolock l(mLock);
1250 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1251 return NO_ERROR;
1252}
1253
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001254status_t MediaPlayerService::Client::setAudioAttributes_l(const Parcel &parcel)
1255{
1256 if (mAudioAttributes != NULL) { free(mAudioAttributes); }
1257 mAudioAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001258 if (mAudioAttributes == NULL) {
1259 return NO_MEMORY;
1260 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001261 unmarshallAudioAttributes(parcel, mAudioAttributes);
1262
1263 ALOGV("setAudioAttributes_l() usage=%d content=%d flags=0x%x tags=%s",
1264 mAudioAttributes->usage, mAudioAttributes->content_type, mAudioAttributes->flags,
1265 mAudioAttributes->tags);
1266
1267 if (mAudioOutput != 0) {
1268 mAudioOutput->setAudioAttributes(mAudioAttributes);
1269 }
1270 return NO_ERROR;
1271}
1272
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001273status_t MediaPlayerService::Client::setLooping(int loop)
1274{
Steve Block3856b092011-10-20 11:56:00 +01001275 ALOGV("[%d] setLooping(%d)", mConnId, loop);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001276 mLoop = loop;
1277 sp<MediaPlayerBase> p = getPlayer();
1278 if (p != 0) return p->setLooping(loop);
1279 return NO_ERROR;
1280}
1281
1282status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1283{
Steve Block3856b092011-10-20 11:56:00 +01001284 ALOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
John Grossman761defc2012-02-09 15:09:05 -08001285
1286 // for hardware output, call player instead
1287 sp<MediaPlayerBase> p = getPlayer();
1288 {
1289 Mutex::Autolock l(mLock);
1290 if (p != 0 && p->hardwareOutput()) {
1291 MediaPlayerHWInterface* hwp =
1292 reinterpret_cast<MediaPlayerHWInterface*>(p.get());
1293 return hwp->setVolume(leftVolume, rightVolume);
1294 } else {
1295 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1296 return NO_ERROR;
1297 }
1298 }
1299
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001300 return NO_ERROR;
1301}
1302
Eric Laurent2beeb502010-07-16 07:43:46 -07001303status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1304{
Steve Block3856b092011-10-20 11:56:00 +01001305 ALOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
Eric Laurent2beeb502010-07-16 07:43:46 -07001306 Mutex::Autolock l(mLock);
1307 if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1308 return NO_ERROR;
1309}
1310
1311status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1312{
Steve Block3856b092011-10-20 11:56:00 +01001313 ALOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
Eric Laurent2beeb502010-07-16 07:43:46 -07001314 Mutex::Autolock l(mLock);
1315 if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1316 return NO_ERROR;
1317}
Nicolas Catania48290382009-07-10 13:53:06 -07001318
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001319status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
Steve Block3856b092011-10-20 11:56:00 +01001320 ALOGV("[%d] setParameter(%d)", mConnId, key);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001321 switch (key) {
1322 case KEY_PARAMETER_AUDIO_ATTRIBUTES:
1323 {
1324 Mutex::Autolock l(mLock);
1325 return setAudioAttributes_l(request);
1326 }
1327 default:
1328 sp<MediaPlayerBase> p = getPlayer();
1329 if (p == 0) { return UNKNOWN_ERROR; }
1330 return p->setParameter(key, request);
1331 }
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001332}
1333
1334status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
Steve Block3856b092011-10-20 11:56:00 +01001335 ALOGV("[%d] getParameter(%d)", mConnId, key);
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001336 sp<MediaPlayerBase> p = getPlayer();
1337 if (p == 0) return UNKNOWN_ERROR;
1338 return p->getParameter(key, reply);
1339}
1340
John Grossmanc795b642012-02-22 15:38:35 -08001341status_t MediaPlayerService::Client::setRetransmitEndpoint(
1342 const struct sockaddr_in* endpoint) {
1343
1344 if (NULL != endpoint) {
1345 uint32_t a = ntohl(endpoint->sin_addr.s_addr);
1346 uint16_t p = ntohs(endpoint->sin_port);
1347 ALOGV("[%d] setRetransmitEndpoint(%u.%u.%u.%u:%hu)", mConnId,
1348 (a >> 24), (a >> 16) & 0xFF, (a >> 8) & 0xFF, (a & 0xFF), p);
1349 } else {
1350 ALOGV("[%d] setRetransmitEndpoint = <none>", mConnId);
1351 }
1352
1353 sp<MediaPlayerBase> p = getPlayer();
1354
1355 // Right now, the only valid time to set a retransmit endpoint is before
1356 // player selection has been made (since the presence or absence of a
1357 // retransmit endpoint is going to determine which player is selected during
1358 // setDataSource).
1359 if (p != 0) return INVALID_OPERATION;
1360
1361 if (NULL != endpoint) {
1362 mRetransmitEndpoint = *endpoint;
1363 mRetransmitEndpointValid = true;
1364 } else {
1365 mRetransmitEndpointValid = false;
1366 }
1367
1368 return NO_ERROR;
1369}
1370
John Grossman44a7e422012-06-21 17:29:24 -07001371status_t MediaPlayerService::Client::getRetransmitEndpoint(
1372 struct sockaddr_in* endpoint)
1373{
1374 if (NULL == endpoint)
1375 return BAD_VALUE;
1376
1377 sp<MediaPlayerBase> p = getPlayer();
1378
1379 if (p != NULL)
1380 return p->getRetransmitEndpoint(endpoint);
1381
1382 if (!mRetransmitEndpointValid)
1383 return NO_INIT;
1384
1385 *endpoint = mRetransmitEndpoint;
1386
1387 return NO_ERROR;
1388}
1389
Gloria Wangb483c472011-04-11 17:23:27 -07001390void MediaPlayerService::Client::notify(
1391 void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001392{
1393 Client* client = static_cast<Client*>(cookie);
James Dongb8a98252012-08-26 16:13:03 -07001394 if (client == NULL) {
1395 return;
1396 }
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001397
James Dongb8a98252012-08-26 16:13:03 -07001398 sp<IMediaPlayerClient> c;
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001399 sp<Client> nextClient;
1400 status_t errStartNext = NO_ERROR;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001401 {
1402 Mutex::Autolock l(client->mLock);
James Dongb8a98252012-08-26 16:13:03 -07001403 c = client->mClient;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001404 if (msg == MEDIA_PLAYBACK_COMPLETE && client->mNextClient != NULL) {
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001405 nextClient = client->mNextClient;
1406
John Grossmancb0b7552012-08-23 17:47:31 -07001407 if (client->mAudioOutput != NULL)
1408 client->mAudioOutput->switchToNextOutput();
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001409
1410 errStartNext = nextClient->start();
1411 }
1412 }
1413
1414 if (nextClient != NULL) {
1415 sp<IMediaPlayerClient> nc;
1416 {
1417 Mutex::Autolock l(nextClient->mLock);
1418 nc = nextClient->mClient;
1419 }
1420 if (nc != NULL) {
1421 if (errStartNext == NO_ERROR) {
1422 nc->notify(MEDIA_INFO, MEDIA_INFO_STARTED_AS_NEXT, 0, obj);
1423 } else {
1424 nc->notify(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN , 0, obj);
1425 ALOGE("gapless:start playback for next track failed, err(%d)", errStartNext);
Wei Jia2afac0c2016-01-07 12:13:07 -08001426 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001427 }
1428 }
1429
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001430 if (MEDIA_INFO == msg &&
Nicolas Catania48290382009-07-10 13:53:06 -07001431 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikoa64c8c72009-07-20 15:07:26 -07001432 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania48290382009-07-10 13:53:06 -07001433
1434 if(client->shouldDropMetadata(metadata_type)) {
1435 return;
1436 }
1437
1438 // Update the list of metadata that have changed. getMetadata
1439 // also access mMetadataUpdated and clears it.
1440 client->addNewMetadataUpdate(metadata_type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001441 }
James Dongb8a98252012-08-26 16:13:03 -07001442
1443 if (c != NULL) {
1444 ALOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
1445 c->notify(msg, ext1, ext2, obj);
1446 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001447}
1448
Nicolas Catania48290382009-07-10 13:53:06 -07001449
nikoa64c8c72009-07-20 15:07:26 -07001450bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001451{
Nicolas Catania48290382009-07-10 13:53:06 -07001452 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001453
Nicolas Catania48290382009-07-10 13:53:06 -07001454 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001455 return true;
1456 }
1457
Nicolas Catania48290382009-07-10 13:53:06 -07001458 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001459 return false;
Nicolas Catania48290382009-07-10 13:53:06 -07001460 } else {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001461 return true;
1462 }
1463}
1464
Nicolas Catania48290382009-07-10 13:53:06 -07001465
nikoa64c8c72009-07-20 15:07:26 -07001466void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania48290382009-07-10 13:53:06 -07001467 Mutex::Autolock lock(mLock);
1468 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1469 mMetadataUpdated.add(metadata_type);
1470 }
1471}
1472
Hassan Shojaniacefac142017-02-06 21:02:02 -08001473// Modular DRM
1474status_t MediaPlayerService::Client::prepareDrm(const uint8_t uuid[16],
1475 const Vector<uint8_t>& drmSessionId)
1476{
1477 ALOGV("[%d] prepareDrm", mConnId);
1478 sp<MediaPlayerBase> p = getPlayer();
1479 if (p == 0) return UNKNOWN_ERROR;
1480
1481 status_t ret = p->prepareDrm(uuid, drmSessionId);
1482 ALOGV("prepareDrm ret: %d", ret);
1483
1484 return ret;
1485}
1486
1487status_t MediaPlayerService::Client::releaseDrm()
1488{
1489 ALOGV("[%d] releaseDrm", mConnId);
1490 sp<MediaPlayerBase> p = getPlayer();
1491 if (p == 0) return UNKNOWN_ERROR;
1492
1493 status_t ret = p->releaseDrm();
1494 ALOGV("releaseDrm ret: %d", ret);
1495
1496 return ret;
1497}
1498
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001499#if CALLBACK_ANTAGONIZER
1500const int Antagonizer::interval = 10000; // 10 msecs
1501
1502Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1503 mExit(false), mActive(false), mClient(client), mCb(cb)
1504{
1505 createThread(callbackThread, this);
1506}
1507
1508void Antagonizer::kill()
1509{
1510 Mutex::Autolock _l(mLock);
1511 mActive = false;
1512 mExit = true;
1513 mCondition.wait(mLock);
1514}
1515
1516int Antagonizer::callbackThread(void* user)
1517{
Steve Blockb8a80522011-12-20 16:23:08 +00001518 ALOGD("Antagonizer started");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001519 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1520 while (!p->mExit) {
1521 if (p->mActive) {
Steve Block3856b092011-10-20 11:56:00 +01001522 ALOGV("send event");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001523 p->mCb(p->mClient, 0, 0, 0);
1524 }
1525 usleep(interval);
1526 }
1527 Mutex::Autolock _l(p->mLock);
1528 p->mCondition.signal();
Steve Blockb8a80522011-12-20 16:23:08 +00001529 ALOGD("Antagonizer stopped");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001530 return 0;
1531}
1532#endif
1533
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001534#undef LOG_TAG
1535#define LOG_TAG "AudioSink"
Andy Hung1afd0982016-11-08 16:13:44 -08001536MediaPlayerService::AudioOutput::AudioOutput(audio_session_t sessionId, uid_t uid, int pid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001537 const audio_attributes_t* attr)
Andreas Huber20111aa2009-07-14 16:56:47 -07001538 : mCallback(NULL),
Eric Laurenta514bdb2010-06-21 09:27:30 -07001539 mCallbackCookie(NULL),
Marco Nelissen6b74d672012-02-28 16:07:44 -08001540 mCallbackData(NULL),
Andy Hungd1c74342015-07-07 16:54:23 -07001541 mStreamType(AUDIO_STREAM_MUSIC),
Andy Hungd1c74342015-07-07 16:54:23 -07001542 mLeftVolume(1.0),
1543 mRightVolume(1.0),
1544 mPlaybackRate(AUDIO_PLAYBACK_RATE_DEFAULT),
1545 mSampleRateHz(0),
1546 mMsecsPerFrame(0),
1547 mFrameSize(0),
Eric Laurent1948eb32012-04-13 16:50:19 -07001548 mSessionId(sessionId),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001549 mUid(uid),
Marco Nelissend457c972014-02-11 08:47:07 -08001550 mPid(pid),
Andy Hungd1c74342015-07-07 16:54:23 -07001551 mSendLevel(0.0),
1552 mAuxEffectId(0),
Andy Hung4ef88d72017-02-21 19:47:53 -08001553 mFlags(AUDIO_OUTPUT_FLAG_NONE),
1554 mVolumeHandler(new VolumeHandler())
Andy Hungd1c74342015-07-07 16:54:23 -07001555{
Steve Block3856b092011-10-20 11:56:00 +01001556 ALOGV("AudioOutput(%d)", sessionId);
Eric Laurent43562692015-07-15 16:49:07 -07001557 if (attr != NULL) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001558 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1559 if (mAttributes != NULL) {
1560 memcpy(mAttributes, attr, sizeof(audio_attributes_t));
1561 mStreamType = audio_attributes_to_stream_type(attr);
1562 }
1563 } else {
1564 mAttributes = NULL;
Eric Laurent43562692015-07-15 16:49:07 -07001565 }
1566
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001567 setMinBufferCount();
1568}
1569
1570MediaPlayerService::AudioOutput::~AudioOutput()
1571{
1572 close();
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001573 free(mAttributes);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001574 delete mCallbackData;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001575}
1576
Andy Hungd1c74342015-07-07 16:54:23 -07001577//static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001578void MediaPlayerService::AudioOutput::setMinBufferCount()
1579{
1580 char value[PROPERTY_VALUE_MAX];
1581 if (property_get("ro.kernel.qemu", value, 0)) {
1582 mIsOnEmulator = true;
1583 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1584 }
1585}
1586
Andy Hungd1c74342015-07-07 16:54:23 -07001587// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001588bool MediaPlayerService::AudioOutput::isOnEmulator()
1589{
Andy Hungd1c74342015-07-07 16:54:23 -07001590 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001591 return mIsOnEmulator;
1592}
1593
Andy Hungd1c74342015-07-07 16:54:23 -07001594// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001595int MediaPlayerService::AudioOutput::getMinBufferCount()
1596{
Andy Hungd1c74342015-07-07 16:54:23 -07001597 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001598 return mMinBufferCount;
1599}
1600
1601ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1602{
Andy Hungd1c74342015-07-07 16:54:23 -07001603 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001604 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001605 return mTrack->frameCount() * mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001606}
1607
1608ssize_t MediaPlayerService::AudioOutput::frameCount() const
1609{
Andy Hungd1c74342015-07-07 16:54:23 -07001610 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001611 if (mTrack == 0) return NO_INIT;
1612 return mTrack->frameCount();
1613}
1614
1615ssize_t MediaPlayerService::AudioOutput::channelCount() const
1616{
Andy Hungd1c74342015-07-07 16:54:23 -07001617 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001618 if (mTrack == 0) return NO_INIT;
1619 return mTrack->channelCount();
1620}
1621
1622ssize_t MediaPlayerService::AudioOutput::frameSize() const
1623{
Andy Hungd1c74342015-07-07 16:54:23 -07001624 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001625 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001626 return mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001627}
1628
1629uint32_t MediaPlayerService::AudioOutput::latency () const
1630{
Andy Hungd1c74342015-07-07 16:54:23 -07001631 Mutex::Autolock lock(mLock);
Eric Laurentdb354e52012-03-05 17:27:11 -08001632 if (mTrack == 0) return 0;
1633 return mTrack->latency();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001634}
1635
1636float MediaPlayerService::AudioOutput::msecsPerFrame() const
1637{
Andy Hungd1c74342015-07-07 16:54:23 -07001638 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001639 return mMsecsPerFrame;
1640}
1641
Marco Nelissen4110c102012-03-29 09:31:28 -07001642status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position) const
Eric Laurent342e9cf2010-01-19 17:37:09 -08001643{
Andy Hungd1c74342015-07-07 16:54:23 -07001644 Mutex::Autolock lock(mLock);
Eric Laurent342e9cf2010-01-19 17:37:09 -08001645 if (mTrack == 0) return NO_INIT;
1646 return mTrack->getPosition(position);
1647}
1648
Lajos Molnar06ad1522014-08-28 07:27:44 -07001649status_t MediaPlayerService::AudioOutput::getTimestamp(AudioTimestamp &ts) const
1650{
Andy Hungd1c74342015-07-07 16:54:23 -07001651 Mutex::Autolock lock(mLock);
Lajos Molnar06ad1522014-08-28 07:27:44 -07001652 if (mTrack == 0) return NO_INIT;
1653 return mTrack->getTimestamp(ts);
1654}
1655
Wei Jiac4ac8172015-10-21 10:35:48 -07001656// TODO: Remove unnecessary calls to getPlayedOutDurationUs()
1657// as it acquires locks and may query the audio driver.
1658//
1659// Some calls could conceivably retrieve extrapolated data instead of
1660// accessing getTimestamp() or getPosition() every time a data buffer with
1661// a media time is received.
1662//
1663// Calculate duration of played samples if played at normal rate (i.e., 1.0).
1664int64_t MediaPlayerService::AudioOutput::getPlayedOutDurationUs(int64_t nowUs) const
1665{
1666 Mutex::Autolock lock(mLock);
1667 if (mTrack == 0 || mSampleRateHz == 0) {
Wei Jia213f4902015-10-22 08:55:25 -07001668 return 0;
Wei Jiac4ac8172015-10-21 10:35:48 -07001669 }
1670
1671 uint32_t numFramesPlayed;
Andy Hung5d313802016-10-10 15:09:39 -07001672 int64_t numFramesPlayedAtUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001673 AudioTimestamp ts;
Wei Jiac4ac8172015-10-21 10:35:48 -07001674
1675 status_t res = mTrack->getTimestamp(ts);
1676 if (res == OK) { // case 1: mixing audio tracks and offloaded tracks.
1677 numFramesPlayed = ts.mPosition;
Andy Hung5d313802016-10-10 15:09:39 -07001678 numFramesPlayedAtUs = ts.mTime.tv_sec * 1000000LL + ts.mTime.tv_nsec / 1000;
1679 //ALOGD("getTimestamp: OK %d %lld", numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001680 } else if (res == WOULD_BLOCK) { // case 2: transitory state on start of a new track
1681 numFramesPlayed = 0;
Andy Hung5d313802016-10-10 15:09:39 -07001682 numFramesPlayedAtUs = nowUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001683 //ALOGD("getTimestamp: WOULD_BLOCK %d %lld",
Andy Hung5d313802016-10-10 15:09:39 -07001684 // numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001685 } else { // case 3: transitory at new track or audio fast tracks.
1686 res = mTrack->getPosition(&numFramesPlayed);
1687 CHECK_EQ(res, (status_t)OK);
Andy Hung5d313802016-10-10 15:09:39 -07001688 numFramesPlayedAtUs = nowUs;
1689 numFramesPlayedAtUs += 1000LL * mTrack->latency() / 2; /* XXX */
1690 //ALOGD("getPosition: %u %lld", numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001691 }
1692
1693 // CHECK_EQ(numFramesPlayed & (1 << 31), 0); // can't be negative until 12.4 hrs, test
1694 // TODO: remove the (int32_t) casting below as it may overflow at 12.4 hours.
1695 int64_t durationUs = (int64_t)((int32_t)numFramesPlayed * 1000000LL / mSampleRateHz)
Andy Hung5d313802016-10-10 15:09:39 -07001696 + nowUs - numFramesPlayedAtUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001697 if (durationUs < 0) {
1698 // Occurs when numFramesPlayed position is very small and the following:
1699 // (1) In case 1, the time nowUs is computed before getTimestamp() is called and
Andy Hung5d313802016-10-10 15:09:39 -07001700 // numFramesPlayedAtUs is greater than nowUs by time more than numFramesPlayed.
Wei Jiac4ac8172015-10-21 10:35:48 -07001701 // (2) In case 3, using getPosition and adding mAudioSink->latency() to
Andy Hung5d313802016-10-10 15:09:39 -07001702 // numFramesPlayedAtUs, by a time amount greater than numFramesPlayed.
Wei Jiac4ac8172015-10-21 10:35:48 -07001703 //
1704 // Both of these are transitory conditions.
1705 ALOGV("getPlayedOutDurationUs: negative duration %lld set to zero", (long long)durationUs);
1706 durationUs = 0;
1707 }
1708 ALOGV("getPlayedOutDurationUs(%lld) nowUs(%lld) frames(%u) framesAt(%lld)",
Andy Hung5d313802016-10-10 15:09:39 -07001709 (long long)durationUs, (long long)nowUs,
1710 numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001711 return durationUs;
1712}
1713
Marco Nelissen4110c102012-03-29 09:31:28 -07001714status_t MediaPlayerService::AudioOutput::getFramesWritten(uint32_t *frameswritten) const
1715{
Andy Hungd1c74342015-07-07 16:54:23 -07001716 Mutex::Autolock lock(mLock);
Marco Nelissen4110c102012-03-29 09:31:28 -07001717 if (mTrack == 0) return NO_INIT;
Andy Hung2f6e73d2016-04-08 12:12:58 -07001718 ExtendedTimestamp ets;
1719 status_t status = mTrack->getTimestamp(&ets);
1720 if (status == OK || status == WOULD_BLOCK) {
1721 *frameswritten = (uint32_t)ets.mPosition[ExtendedTimestamp::LOCATION_CLIENT];
1722 }
1723 return status;
Marco Nelissen4110c102012-03-29 09:31:28 -07001724}
1725
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001726status_t MediaPlayerService::AudioOutput::setParameters(const String8& keyValuePairs)
1727{
Andy Hungd1c74342015-07-07 16:54:23 -07001728 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001729 if (mTrack == 0) return NO_INIT;
1730 return mTrack->setParameters(keyValuePairs);
1731}
1732
1733String8 MediaPlayerService::AudioOutput::getParameters(const String8& keys)
1734{
Andy Hungd1c74342015-07-07 16:54:23 -07001735 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001736 if (mTrack == 0) return String8::empty();
1737 return mTrack->getParameters(keys);
1738}
1739
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001740void MediaPlayerService::AudioOutput::setAudioAttributes(const audio_attributes_t * attributes) {
Andy Hungd1c74342015-07-07 16:54:23 -07001741 Mutex::Autolock lock(mLock);
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001742 if (attributes == NULL) {
1743 free(mAttributes);
1744 mAttributes = NULL;
1745 } else {
1746 if (mAttributes == NULL) {
1747 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1748 }
1749 memcpy(mAttributes, attributes, sizeof(audio_attributes_t));
Eric Laurent43562692015-07-15 16:49:07 -07001750 mStreamType = audio_attributes_to_stream_type(attributes);
1751 }
1752}
1753
1754void MediaPlayerService::AudioOutput::setAudioStreamType(audio_stream_type_t streamType)
1755{
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001756 Mutex::Autolock lock(mLock);
Eric Laurent43562692015-07-15 16:49:07 -07001757 // do not allow direct stream type modification if attributes have been set
1758 if (mAttributes == NULL) {
1759 mStreamType = streamType;
1760 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001761}
1762
Andy Hungd1c74342015-07-07 16:54:23 -07001763void MediaPlayerService::AudioOutput::deleteRecycledTrack_l()
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001764{
Andy Hungd1c74342015-07-07 16:54:23 -07001765 ALOGV("deleteRecycledTrack_l");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001766 if (mRecycledTrack != 0) {
1767
1768 if (mCallbackData != NULL) {
1769 mCallbackData->setOutput(NULL);
1770 mCallbackData->endTrackSwitch();
1771 }
1772
1773 if ((mRecycledTrack->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) {
Andy Hunge13f8a62016-03-30 14:20:42 -07001774 int32_t msec = 0;
1775 if (!mRecycledTrack->stopped()) { // check if active
1776 (void)mRecycledTrack->pendingDuration(&msec);
1777 }
1778 mRecycledTrack->stop(); // ensure full data drain
1779 ALOGD("deleting recycled track, waiting for data drain (%d msec)", msec);
1780 if (msec > 0) {
1781 static const int32_t WAIT_LIMIT_MS = 3000;
1782 if (msec > WAIT_LIMIT_MS) {
1783 msec = WAIT_LIMIT_MS;
1784 }
1785 usleep(msec * 1000LL);
1786 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001787 }
1788 // An offloaded track isn't flushed because the STREAM_END is reported
1789 // slightly prematurely to allow time for the gapless track switch
1790 // but this means that if we decide not to recycle the track there
1791 // could be a small amount of residual data still playing. We leave
1792 // AudioFlinger to drain the track.
1793
1794 mRecycledTrack.clear();
Andy Hungd1c74342015-07-07 16:54:23 -07001795 close_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001796 delete mCallbackData;
1797 mCallbackData = NULL;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001798 }
1799}
1800
Andy Hungd1c74342015-07-07 16:54:23 -07001801void MediaPlayerService::AudioOutput::close_l()
1802{
1803 mTrack.clear();
1804}
1805
Andreas Huber20111aa2009-07-14 16:56:47 -07001806status_t MediaPlayerService::AudioOutput::open(
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001807 uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
1808 audio_format_t format, int bufferCount,
Eric Laurent1948eb32012-04-13 16:50:19 -07001809 AudioCallback cb, void *cookie,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001810 audio_output_flags_t flags,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001811 const audio_offload_info_t *offloadInfo,
Andy Hung179652e2015-05-31 22:49:46 -07001812 bool doNotReconnect,
1813 uint32_t suggestedFrameCount)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001814{
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001815 ALOGV("open(%u, %d, 0x%x, 0x%x, %d, %d 0x%x)", sampleRate, channelCount, channelMask,
1816 format, bufferCount, mSessionId, flags);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001817
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001818 // offloading is only supported in callback mode for now.
1819 // offloadInfo must be present if offload flag is set
1820 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) &&
1821 ((cb == NULL) || (offloadInfo == NULL))) {
1822 return BAD_VALUE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001823 }
1824
Andy Hung179652e2015-05-31 22:49:46 -07001825 // compute frame count for the AudioTrack internal buffer
1826 size_t frameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001827 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1828 frameCount = 0; // AudioTrack will get frame count from AudioFlinger
1829 } else {
Andy Hung179652e2015-05-31 22:49:46 -07001830 // try to estimate the buffer processing fetch size from AudioFlinger.
1831 // framesPerBuffer is approximate and generally correct, except when it's not :-).
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001832 uint32_t afSampleRate;
1833 size_t afFrameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001834 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1835 return NO_INIT;
1836 }
1837 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1838 return NO_INIT;
1839 }
Andy Hung179652e2015-05-31 22:49:46 -07001840 const size_t framesPerBuffer =
1841 (unsigned long long)sampleRate * afFrameCount / afSampleRate;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001842
Andy Hung179652e2015-05-31 22:49:46 -07001843 if (bufferCount == 0) {
1844 // use suggestedFrameCount
1845 bufferCount = (suggestedFrameCount + framesPerBuffer - 1) / framesPerBuffer;
1846 }
1847 // Check argument bufferCount against the mininum buffer count
1848 if (bufferCount != 0 && bufferCount < mMinBufferCount) {
1849 ALOGV("bufferCount (%d) increased to %d", bufferCount, mMinBufferCount);
1850 bufferCount = mMinBufferCount;
1851 }
1852 // if frameCount is 0, then AudioTrack will get frame count from AudioFlinger
1853 // which will be the minimum size permitted.
1854 frameCount = bufferCount * framesPerBuffer;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001855 }
Andreas Huber20111aa2009-07-14 16:56:47 -07001856
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001857 if (channelMask == CHANNEL_MASK_USE_CHANNEL_ORDER) {
Glenn Kastenab334fd2012-03-14 12:56:06 -07001858 channelMask = audio_channel_out_mask_from_count(channelCount);
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001859 if (0 == channelMask) {
1860 ALOGE("open() error, can\'t derive mask for %d audio channels", channelCount);
1861 return NO_INIT;
1862 }
1863 }
Eric Laurent1948eb32012-04-13 16:50:19 -07001864
Andy Hungd1c74342015-07-07 16:54:23 -07001865 Mutex::Autolock lock(mLock);
Andy Hung179652e2015-05-31 22:49:46 -07001866 mCallback = cb;
1867 mCallbackCookie = cookie;
1868
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001869 // Check whether we can recycle the track
1870 bool reuse = false;
1871 bool bothOffloaded = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001872
Glenn Kasten2799d742013-05-30 14:33:29 -07001873 if (mRecycledTrack != 0) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001874 // check whether we are switching between two offloaded tracks
1875 bothOffloaded = (flags & mRecycledTrack->getFlags()
1876 & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0;
Marco Nelissen67295b52012-06-11 14:52:53 -07001877
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001878 // check if the existing track can be reused as-is, or if a new track needs to be created.
1879 reuse = true;
1880
Marco Nelissen67295b52012-06-11 14:52:53 -07001881 if ((mCallbackData == NULL && mCallback != NULL) ||
1882 (mCallbackData != NULL && mCallback == NULL)) {
1883 // recycled track uses callbacks but the caller wants to use writes, or vice versa
1884 ALOGV("can't chain callback and write");
1885 reuse = false;
1886 } else if ((mRecycledTrack->getSampleRate() != sampleRate) ||
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001887 (mRecycledTrack->channelCount() != (uint32_t)channelCount) ) {
1888 ALOGV("samplerate, channelcount differ: %u/%u Hz, %u/%d ch",
Marco Nelissen67295b52012-06-11 14:52:53 -07001889 mRecycledTrack->getSampleRate(), sampleRate,
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001890 mRecycledTrack->channelCount(), channelCount);
Marco Nelissen67295b52012-06-11 14:52:53 -07001891 reuse = false;
1892 } else if (flags != mFlags) {
1893 ALOGV("output flags differ %08x/%08x", flags, mFlags);
1894 reuse = false;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001895 } else if (mRecycledTrack->format() != format) {
1896 reuse = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001897 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001898 } else {
1899 ALOGV("no track available to recycle");
1900 }
1901
1902 ALOGV_IF(bothOffloaded, "both tracks offloaded");
1903
1904 // If we can't recycle and both tracks are offloaded
1905 // we must close the previous output before opening a new one
1906 if (bothOffloaded && !reuse) {
1907 ALOGV("both offloaded and not recycling");
Andy Hungd1c74342015-07-07 16:54:23 -07001908 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001909 }
1910
1911 sp<AudioTrack> t;
1912 CallbackData *newcbd = NULL;
1913
1914 // We don't attempt to create a new track if we are recycling an
1915 // offloaded track. But, if we are recycling a non-offloaded or we
1916 // are switching where one is offloaded and one isn't then we create
1917 // the new track in advance so that we can read additional stream info
1918
1919 if (!(reuse && bothOffloaded)) {
1920 ALOGV("creating new AudioTrack");
1921
1922 if (mCallback != NULL) {
1923 newcbd = new CallbackData(this);
1924 t = new AudioTrack(
1925 mStreamType,
1926 sampleRate,
1927 format,
1928 channelMask,
1929 frameCount,
1930 flags,
1931 CallbackWrapper,
1932 newcbd,
1933 0, // notification frames
1934 mSessionId,
1935 AudioTrack::TRANSFER_CALLBACK,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001936 offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -08001937 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001938 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001939 mAttributes,
1940 doNotReconnect);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001941 } else {
Andy Hungff874dc2016-04-11 16:49:09 -07001942 // TODO: Due to buffer memory concerns, we use a max target playback speed
1943 // based on mPlaybackRate at the time of open (instead of kMaxRequiredSpeed),
1944 // also clamping the target speed to 1.0 <= targetSpeed <= kMaxRequiredSpeed.
1945 const float targetSpeed =
1946 std::min(std::max(mPlaybackRate.mSpeed, 1.0f), kMaxRequiredSpeed);
1947 ALOGW_IF(targetSpeed != mPlaybackRate.mSpeed,
1948 "track target speed:%f clamped from playback speed:%f",
1949 targetSpeed, mPlaybackRate.mSpeed);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001950 t = new AudioTrack(
1951 mStreamType,
1952 sampleRate,
1953 format,
1954 channelMask,
1955 frameCount,
1956 flags,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001957 NULL, // callback
1958 NULL, // user data
1959 0, // notification frames
1960 mSessionId,
1961 AudioTrack::TRANSFER_DEFAULT,
1962 NULL, // offload info
Marco Nelissend457c972014-02-11 08:47:07 -08001963 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001964 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001965 mAttributes,
Andy Hungff874dc2016-04-11 16:49:09 -07001966 doNotReconnect,
1967 targetSpeed);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001968 }
1969
1970 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1971 ALOGE("Unable to create audio track");
1972 delete newcbd;
Glenn Kasten3e98ecd2015-05-18 13:13:24 -07001973 // t goes out of scope, so reference count drops to zero
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001974 return NO_INIT;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001975 } else {
1976 // successful AudioTrack initialization implies a legacy stream type was generated
1977 // from the audio attributes
1978 mStreamType = t->streamType();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001979 }
1980 }
1981
1982 if (reuse) {
1983 CHECK(mRecycledTrack != NULL);
1984
1985 if (!bothOffloaded) {
1986 if (mRecycledTrack->frameCount() != t->frameCount()) {
Andy Hung833b4752016-04-04 17:15:48 -07001987 ALOGV("framecount differs: %zu/%zu frames",
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001988 mRecycledTrack->frameCount(), t->frameCount());
1989 reuse = false;
1990 }
1991 }
1992
Marco Nelissen67295b52012-06-11 14:52:53 -07001993 if (reuse) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001994 ALOGV("chaining to next output and recycling track");
Andy Hungd1c74342015-07-07 16:54:23 -07001995 close_l();
Marco Nelissen67295b52012-06-11 14:52:53 -07001996 mTrack = mRecycledTrack;
Glenn Kasten2799d742013-05-30 14:33:29 -07001997 mRecycledTrack.clear();
Marco Nelissen67295b52012-06-11 14:52:53 -07001998 if (mCallbackData != NULL) {
1999 mCallbackData->setOutput(this);
2000 }
Marco Nelissen67295b52012-06-11 14:52:53 -07002001 delete newcbd;
Wei Jiae0bbac92016-07-18 16:04:53 -07002002 return updateTrack();
Marco Nelissen67295b52012-06-11 14:52:53 -07002003 }
Marco Nelissen67295b52012-06-11 14:52:53 -07002004 }
2005
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002006 // we're not going to reuse the track, unblock and flush it
2007 // this was done earlier if both tracks are offloaded
2008 if (!bothOffloaded) {
Andy Hungd1c74342015-07-07 16:54:23 -07002009 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002010 }
2011
2012 CHECK((t != NULL) && ((mCallback == NULL) || (newcbd != NULL)));
2013
Marco Nelissen67295b52012-06-11 14:52:53 -07002014 mCallbackData = newcbd;
Steve Block3856b092011-10-20 11:56:00 +01002015 ALOGV("setVolume");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002016 t->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07002017
Andy Hung39399b62017-04-21 15:07:45 -07002018 // Restore VolumeShapers for the MediaPlayer in case the track was recreated
2019 // due to an output sink error (e.g. offload to non-offload switch).
2020 mVolumeHandler->forall([&t](const VolumeShaper &shaper) -> VolumeShaper::Status {
2021 sp<VolumeShaper::Operation> operationToEnd =
2022 new VolumeShaper::Operation(shaper.mOperation);
2023 // TODO: Ideally we would restore to the exact xOffset position
2024 // as returned by getVolumeShaperState(), but we don't have that
2025 // information when restoring at the client unless we periodically poll
2026 // the server or create shared memory state.
2027 //
2028 // For now, we simply advance to the end of the VolumeShaper effect
2029 // if it has been started.
2030 if (shaper.isStarted()) {
2031 operationToEnd->setXOffset(1.f);
2032 }
2033 return t->applyVolumeShaper(shaper.mConfiguration, operationToEnd);
Andy Hung4ef88d72017-02-21 19:47:53 -08002034 });
Andy Hung4ef88d72017-02-21 19:47:53 -08002035
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002036 mSampleRateHz = sampleRate;
Preetam Singh Ranawat2e17eef2015-08-12 12:11:46 -07002037 mFlags = flags;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002038 mMsecsPerFrame = 1E3f / (mPlaybackRate.mSpeed * sampleRate);
Andy Hungd1c74342015-07-07 16:54:23 -07002039 mFrameSize = t->frameSize();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002040 mTrack = t;
Eric Laurent2beeb502010-07-16 07:43:46 -07002041
Wei Jiae0bbac92016-07-18 16:04:53 -07002042 return updateTrack();
2043}
2044
2045status_t MediaPlayerService::AudioOutput::updateTrack() {
2046 if (mTrack == NULL) {
2047 return NO_ERROR;
2048 }
2049
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002050 status_t res = NO_ERROR;
Wei Jia0162d002015-06-09 11:59:33 -07002051 // Note some output devices may give us a direct track even though we don't specify it.
2052 // Example: Line application b/17459982.
Wei Jiae0bbac92016-07-18 16:04:53 -07002053 if ((mTrack->getFlags()
2054 & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) {
2055 res = mTrack->setPlaybackRate(mPlaybackRate);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002056 if (res == NO_ERROR) {
Wei Jiae0bbac92016-07-18 16:04:53 -07002057 mTrack->setAuxEffectSendLevel(mSendLevel);
2058 res = mTrack->attachAuxEffect(mAuxEffectId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002059 }
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002060 }
Wei Jiae0bbac92016-07-18 16:04:53 -07002061 ALOGV("updateTrack() DONE status %d", res);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002062 return res;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002063}
2064
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002065status_t MediaPlayerService::AudioOutput::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002066{
Steve Block3856b092011-10-20 11:56:00 +01002067 ALOGV("start");
Andy Hungd1c74342015-07-07 16:54:23 -07002068 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08002069 if (mCallbackData != NULL) {
2070 mCallbackData->endTrackSwitch();
2071 }
Glenn Kasten2799d742013-05-30 14:33:29 -07002072 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002073 mTrack->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07002074 mTrack->setAuxEffectSendLevel(mSendLevel);
Andy Hung39399b62017-04-21 15:07:45 -07002075 status_t status = mTrack->start();
2076 if (status == NO_ERROR) {
2077 mVolumeHandler->setStarted();
2078 }
2079 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002080 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002081 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002082}
2083
Marco Nelissen6b74d672012-02-28 16:07:44 -08002084void MediaPlayerService::AudioOutput::setNextOutput(const sp<AudioOutput>& nextOutput) {
Andy Hungd1c74342015-07-07 16:54:23 -07002085 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08002086 mNextOutput = nextOutput;
2087}
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08002088
Marco Nelissen6b74d672012-02-28 16:07:44 -08002089void MediaPlayerService::AudioOutput::switchToNextOutput() {
2090 ALOGV("switchToNextOutput");
Andy Hungd1c74342015-07-07 16:54:23 -07002091
2092 // Try to acquire the callback lock before moving track (without incurring deadlock).
2093 const unsigned kMaxSwitchTries = 100;
2094 Mutex::Autolock lock(mLock);
2095 for (unsigned tries = 0;;) {
2096 if (mTrack == 0) {
2097 return;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002098 }
Andy Hungd1c74342015-07-07 16:54:23 -07002099 if (mNextOutput != NULL && mNextOutput != this) {
2100 if (mCallbackData != NULL) {
2101 // two alternative approaches
2102#if 1
2103 CallbackData *callbackData = mCallbackData;
2104 mLock.unlock();
2105 // proper acquisition sequence
2106 callbackData->lock();
2107 mLock.lock();
2108 // Caution: it is unlikely that someone deleted our callback or changed our target
2109 if (callbackData != mCallbackData || mNextOutput == NULL || mNextOutput == this) {
2110 // fatal if we are starved out.
2111 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
2112 "switchToNextOutput() cannot obtain correct lock sequence");
2113 callbackData->unlock();
2114 continue;
2115 }
2116 callbackData->mSwitching = true; // begin track switch
Wei Jiaadee56a2016-08-05 15:40:34 -07002117 callbackData->setOutput(NULL);
Andy Hungd1c74342015-07-07 16:54:23 -07002118#else
2119 // tryBeginTrackSwitch() returns false if the callback has the lock.
2120 if (!mCallbackData->tryBeginTrackSwitch()) {
2121 // fatal if we are starved out.
2122 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
2123 "switchToNextOutput() cannot obtain callback lock");
2124 mLock.unlock();
2125 usleep(5 * 1000 /* usec */); // allow callback to use AudioOutput
2126 mLock.lock();
2127 continue;
2128 }
2129#endif
2130 }
2131
2132 Mutex::Autolock nextLock(mNextOutput->mLock);
2133
2134 // If the next output track is not NULL, then it has been
2135 // opened already for playback.
2136 // This is possible even without the next player being started,
2137 // for example, the next player could be prepared and seeked.
2138 //
2139 // Presuming it isn't advisable to force the track over.
2140 if (mNextOutput->mTrack == NULL) {
2141 ALOGD("Recycling track for gapless playback");
2142 delete mNextOutput->mCallbackData;
2143 mNextOutput->mCallbackData = mCallbackData;
2144 mNextOutput->mRecycledTrack = mTrack;
2145 mNextOutput->mSampleRateHz = mSampleRateHz;
2146 mNextOutput->mMsecsPerFrame = mMsecsPerFrame;
Andy Hungd1c74342015-07-07 16:54:23 -07002147 mNextOutput->mFlags = mFlags;
2148 mNextOutput->mFrameSize = mFrameSize;
2149 close_l();
2150 mCallbackData = NULL; // destruction handled by mNextOutput
2151 } else {
2152 ALOGW("Ignoring gapless playback because next player has already started");
2153 // remove track in case resource needed for future players.
2154 if (mCallbackData != NULL) {
2155 mCallbackData->endTrackSwitch(); // release lock for callbacks before close.
2156 }
2157 close_l();
2158 }
2159 }
2160 break;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002161 }
2162}
2163
Wei Jia7d3f4df2015-03-03 15:28:00 -08002164ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002165{
Andy Hungd1c74342015-07-07 16:54:23 -07002166 Mutex::Autolock lock(mLock);
Glenn Kastenadad3d72014-02-21 14:51:43 -08002167 LOG_ALWAYS_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
Andreas Huber20111aa2009-07-14 16:56:47 -07002168
Steve Block3856b092011-10-20 11:56:00 +01002169 //ALOGV("write(%p, %u)", buffer, size);
Glenn Kasten2799d742013-05-30 14:33:29 -07002170 if (mTrack != 0) {
Andy Hung2f6e73d2016-04-08 12:12:58 -07002171 return mTrack->write(buffer, size, blocking);
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07002172 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002173 return NO_INIT;
2174}
2175
2176void MediaPlayerService::AudioOutput::stop()
2177{
Steve Block3856b092011-10-20 11:56:00 +01002178 ALOGV("stop");
Andy Hungd1c74342015-07-07 16:54:23 -07002179 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002180 if (mTrack != 0) mTrack->stop();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002181}
2182
2183void MediaPlayerService::AudioOutput::flush()
2184{
Steve Block3856b092011-10-20 11:56:00 +01002185 ALOGV("flush");
Andy Hungd1c74342015-07-07 16:54:23 -07002186 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002187 if (mTrack != 0) mTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002188}
2189
2190void MediaPlayerService::AudioOutput::pause()
2191{
Steve Block3856b092011-10-20 11:56:00 +01002192 ALOGV("pause");
Andy Hungd1c74342015-07-07 16:54:23 -07002193 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002194 if (mTrack != 0) mTrack->pause();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002195}
2196
2197void MediaPlayerService::AudioOutput::close()
2198{
Steve Block3856b092011-10-20 11:56:00 +01002199 ALOGV("close");
Erik Wolsheimer7845a1f2015-10-30 12:07:52 -07002200 sp<AudioTrack> track;
2201 {
2202 Mutex::Autolock lock(mLock);
2203 track = mTrack;
2204 close_l(); // clears mTrack
2205 }
2206 // destruction of the track occurs outside of mutex.
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002207}
2208
2209void MediaPlayerService::AudioOutput::setVolume(float left, float right)
2210{
Steve Block3856b092011-10-20 11:56:00 +01002211 ALOGV("setVolume(%f, %f)", left, right);
Andy Hungd1c74342015-07-07 16:54:23 -07002212 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002213 mLeftVolume = left;
2214 mRightVolume = right;
Glenn Kasten2799d742013-05-30 14:33:29 -07002215 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002216 mTrack->setVolume(left, right);
2217 }
2218}
2219
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002220status_t MediaPlayerService::AudioOutput::setPlaybackRate(const AudioPlaybackRate &rate)
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002221{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002222 ALOGV("setPlaybackRate(%f %f %d %d)",
2223 rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Andy Hungd1c74342015-07-07 16:54:23 -07002224 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002225 if (mTrack == 0) {
2226 // remember rate so that we can set it when the track is opened
2227 mPlaybackRate = rate;
2228 return OK;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002229 }
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002230 status_t res = mTrack->setPlaybackRate(rate);
2231 if (res != NO_ERROR) {
2232 return res;
2233 }
2234 // rate.mSpeed is always greater than 0 if setPlaybackRate succeeded
2235 CHECK_GT(rate.mSpeed, 0.f);
2236 mPlaybackRate = rate;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002237 if (mSampleRateHz != 0) {
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002238 mMsecsPerFrame = 1E3f / (rate.mSpeed * mSampleRateHz);
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002239 }
2240 return res;
2241}
2242
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002243status_t MediaPlayerService::AudioOutput::getPlaybackRate(AudioPlaybackRate *rate)
2244{
2245 ALOGV("setPlaybackRate");
Andy Hungd1c74342015-07-07 16:54:23 -07002246 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002247 if (mTrack == 0) {
2248 return NO_INIT;
2249 }
2250 *rate = mTrack->getPlaybackRate();
2251 return NO_ERROR;
2252}
2253
Eric Laurent2beeb502010-07-16 07:43:46 -07002254status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
2255{
Steve Block3856b092011-10-20 11:56:00 +01002256 ALOGV("setAuxEffectSendLevel(%f)", level);
Andy Hungd1c74342015-07-07 16:54:23 -07002257 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002258 mSendLevel = level;
Glenn Kasten2799d742013-05-30 14:33:29 -07002259 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002260 return mTrack->setAuxEffectSendLevel(level);
2261 }
2262 return NO_ERROR;
2263}
2264
2265status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
2266{
Steve Block3856b092011-10-20 11:56:00 +01002267 ALOGV("attachAuxEffect(%d)", effectId);
Andy Hungd1c74342015-07-07 16:54:23 -07002268 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002269 mAuxEffectId = effectId;
Glenn Kasten2799d742013-05-30 14:33:29 -07002270 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002271 return mTrack->attachAuxEffect(effectId);
2272 }
2273 return NO_ERROR;
2274}
2275
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002276VolumeShaper::Status MediaPlayerService::AudioOutput::applyVolumeShaper(
2277 const sp<VolumeShaper::Configuration>& configuration,
2278 const sp<VolumeShaper::Operation>& operation)
2279{
2280 Mutex::Autolock lock(mLock);
2281 ALOGV("AudioOutput::applyVolumeShaper");
Andy Hung4ef88d72017-02-21 19:47:53 -08002282
Andy Hung4ef88d72017-02-21 19:47:53 -08002283 mVolumeHandler->setIdIfNecessary(configuration);
Andy Hung39399b62017-04-21 15:07:45 -07002284
2285 VolumeShaper::Status status;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002286 if (mTrack != 0) {
Andy Hung39399b62017-04-21 15:07:45 -07002287 status = mTrack->applyVolumeShaper(configuration, operation);
2288 if (status >= 0) {
2289 (void)mVolumeHandler->applyVolumeShaper(configuration, operation);
2290 // TODO: start on exact AudioTrack state (STATE_ACTIVE || STATE_STOPPING)
2291 mVolumeHandler->setStarted();
2292 }
Andy Hung4ef88d72017-02-21 19:47:53 -08002293 } else {
Andy Hung39399b62017-04-21 15:07:45 -07002294 status = mVolumeHandler->applyVolumeShaper(configuration, operation);
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002295 }
Andy Hung39399b62017-04-21 15:07:45 -07002296 return status;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002297}
2298
2299sp<VolumeShaper::State> MediaPlayerService::AudioOutput::getVolumeShaperState(int id)
2300{
2301 Mutex::Autolock lock(mLock);
2302 if (mTrack != 0) {
2303 return mTrack->getVolumeShaperState(id);
Andy Hung4ef88d72017-02-21 19:47:53 -08002304 } else {
2305 return mVolumeHandler->getVolumeShaperState(id);
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002306 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002307}
2308
Andreas Huber20111aa2009-07-14 16:56:47 -07002309// static
2310void MediaPlayerService::AudioOutput::CallbackWrapper(
Glenn Kastend217a8c2011-06-01 15:20:35 -07002311 int event, void *cookie, void *info) {
Steve Block3856b092011-10-20 11:56:00 +01002312 //ALOGV("callbackwrapper");
Marco Nelissen6b74d672012-02-28 16:07:44 -08002313 CallbackData *data = (CallbackData*)cookie;
Andy Hungd1c74342015-07-07 16:54:23 -07002314 // lock to ensure we aren't caught in the middle of a track switch.
Marco Nelissen6b74d672012-02-28 16:07:44 -08002315 data->lock();
2316 AudioOutput *me = data->getOutput();
Andreas Huber20111aa2009-07-14 16:56:47 -07002317 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002318 if (me == NULL) {
2319 // no output set, likely because the track was scheduled to be reused
2320 // by another player, but the format turned out to be incompatible.
2321 data->unlock();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002322 if (buffer != NULL) {
2323 buffer->size = 0;
2324 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08002325 return;
2326 }
Andreas Huber20111aa2009-07-14 16:56:47 -07002327
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002328 switch(event) {
2329 case AudioTrack::EVENT_MORE_DATA: {
2330 size_t actualSize = (*me->mCallback)(
2331 me, buffer->raw, buffer->size, me->mCallbackCookie,
2332 CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002333
Andy Hung719b46b2015-05-31 22:18:25 -07002334 // Log when no data is returned from the callback.
2335 // (1) We may have no data (especially with network streaming sources).
2336 // (2) We may have reached the EOS and the audio track is not stopped yet.
2337 // Note that AwesomePlayer/AudioPlayer will only return zero size when it reaches the EOS.
2338 // NuPlayerRenderer will return zero when it doesn't have data (it doesn't block to fill).
2339 //
2340 // This is a benign busy-wait, with the next data request generated 10 ms or more later;
2341 // nevertheless for power reasons, we don't want to see too many of these.
Andreas Huber2e8ffaf2010-02-18 16:45:13 -08002342
Andy Hung719b46b2015-05-31 22:18:25 -07002343 ALOGV_IF(actualSize == 0 && buffer->size > 0, "callbackwrapper: empty buffer returned");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002344
2345 buffer->size = actualSize;
2346 } break;
2347
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002348 case AudioTrack::EVENT_STREAM_END:
Andy Hung719b46b2015-05-31 22:18:25 -07002349 // currently only occurs for offloaded callbacks
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002350 ALOGV("callbackwrapper: deliver EVENT_STREAM_END");
2351 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2352 me->mCallbackCookie, CB_EVENT_STREAM_END);
2353 break;
2354
2355 case AudioTrack::EVENT_NEW_IAUDIOTRACK :
2356 ALOGV("callbackwrapper: deliver EVENT_TEAR_DOWN");
2357 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2358 me->mCallbackCookie, CB_EVENT_TEAR_DOWN);
2359 break;
2360
Glenn Kasten421743b2015-06-01 08:18:08 -07002361 case AudioTrack::EVENT_UNDERRUN:
Andy Hung719b46b2015-05-31 22:18:25 -07002362 // This occurs when there is no data available, typically
Glenn Kasten421743b2015-06-01 08:18:08 -07002363 // when there is a failure to supply data to the AudioTrack. It can also
2364 // occur in non-offloaded mode when the audio device comes out of standby.
2365 //
Andy Hung719b46b2015-05-31 22:18:25 -07002366 // If an AudioTrack underruns it outputs silence. Since this happens suddenly
2367 // it may sound like an audible pop or glitch.
2368 //
2369 // The underrun event is sent once per track underrun; the condition is reset
2370 // when more data is sent to the AudioTrack.
Eric Laurente93cc032016-05-05 10:15:10 -07002371 ALOGD("callbackwrapper: EVENT_UNDERRUN (discarded)");
Glenn Kasten421743b2015-06-01 08:18:08 -07002372 break;
2373
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002374 default:
2375 ALOGE("received unknown event type: %d inside CallbackWrapper !", event);
Andreas Huber51c1e0e2011-04-04 11:43:40 -07002376 }
2377
Marco Nelissen6b74d672012-02-28 16:07:44 -08002378 data->unlock();
Andreas Huber20111aa2009-07-14 16:56:47 -07002379}
2380
Glenn Kastend848eb42016-03-08 13:42:11 -08002381audio_session_t MediaPlayerService::AudioOutput::getSessionId() const
Eric Laurent8c563ed2010-10-07 18:23:03 -07002382{
Andy Hungd1c74342015-07-07 16:54:23 -07002383 Mutex::Autolock lock(mLock);
Eric Laurent8c563ed2010-10-07 18:23:03 -07002384 return mSessionId;
2385}
2386
Eric Laurent6f59db12013-07-26 17:16:50 -07002387uint32_t MediaPlayerService::AudioOutput::getSampleRate() const
2388{
Andy Hungd1c74342015-07-07 16:54:23 -07002389 Mutex::Autolock lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -07002390 if (mTrack == 0) return 0;
2391 return mTrack->getSampleRate();
2392}
2393
Andy Hungf2c87b32016-04-07 19:49:29 -07002394int64_t MediaPlayerService::AudioOutput::getBufferDurationInUs() const
2395{
2396 Mutex::Autolock lock(mLock);
2397 if (mTrack == 0) {
2398 return 0;
2399 }
2400 int64_t duration;
2401 if (mTrack->getBufferDurationInUs(&duration) != OK) {
2402 return 0;
2403 }
2404 return duration;
2405}
2406
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002407////////////////////////////////////////////////////////////////////////////////
2408
2409struct CallbackThread : public Thread {
2410 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
2411 MediaPlayerBase::AudioSink::AudioCallback cb,
2412 void *cookie);
2413
2414protected:
2415 virtual ~CallbackThread();
2416
2417 virtual bool threadLoop();
2418
2419private:
2420 wp<MediaPlayerBase::AudioSink> mSink;
2421 MediaPlayerBase::AudioSink::AudioCallback mCallback;
2422 void *mCookie;
2423 void *mBuffer;
2424 size_t mBufferSize;
2425
2426 CallbackThread(const CallbackThread &);
2427 CallbackThread &operator=(const CallbackThread &);
2428};
2429
2430CallbackThread::CallbackThread(
2431 const wp<MediaPlayerBase::AudioSink> &sink,
2432 MediaPlayerBase::AudioSink::AudioCallback cb,
2433 void *cookie)
2434 : mSink(sink),
2435 mCallback(cb),
2436 mCookie(cookie),
2437 mBuffer(NULL),
2438 mBufferSize(0) {
2439}
2440
2441CallbackThread::~CallbackThread() {
2442 if (mBuffer) {
2443 free(mBuffer);
2444 mBuffer = NULL;
2445 }
2446}
2447
2448bool CallbackThread::threadLoop() {
2449 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
2450 if (sink == NULL) {
2451 return false;
2452 }
2453
2454 if (mBuffer == NULL) {
2455 mBufferSize = sink->bufferSize();
2456 mBuffer = malloc(mBufferSize);
2457 }
2458
2459 size_t actualSize =
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002460 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie,
2461 MediaPlayerBase::AudioSink::CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002462
2463 if (actualSize > 0) {
2464 sink->write(mBuffer, actualSize);
Andy Hunga31335a2014-08-20 17:37:59 -07002465 // Could return false on sink->write() error or short count.
2466 // Not necessarily appropriate but would work for AudioCache behavior.
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002467 }
2468
2469 return true;
2470}
2471
2472////////////////////////////////////////////////////////////////////////////////
2473
Chong Zhange5b9b692017-05-11 11:44:56 -07002474void MediaPlayerService::addBatteryData(uint32_t params) {
2475 mBatteryTracker.addBatteryData(params);
2476}
2477
2478status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
2479 return mBatteryTracker.pullBatteryData(reply);
2480}
2481
2482MediaPlayerService::BatteryTracker::BatteryTracker() {
2483 mBatteryAudio.refCount = 0;
2484 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2485 mBatteryAudio.deviceOn[i] = 0;
2486 mBatteryAudio.lastTime[i] = 0;
2487 mBatteryAudio.totalTime[i] = 0;
2488 }
2489 // speaker is on by default
2490 mBatteryAudio.deviceOn[SPEAKER] = 1;
2491
2492 // reset battery stats
2493 // if the mediaserver has crashed, battery stats could be left
2494 // in bad state, reset the state upon service start.
2495 BatteryNotifier::getInstance().noteResetVideo();
2496}
2497
2498void MediaPlayerService::BatteryTracker::addBatteryData(uint32_t params)
Gloria Wang7cf180c2011-02-19 18:37:57 -08002499{
2500 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002501
2502 int32_t time = systemTime() / 1000000L;
2503
2504 // change audio output devices. This notification comes from AudioFlinger
2505 if ((params & kBatteryDataSpeakerOn)
2506 || (params & kBatteryDataOtherAudioDeviceOn)) {
2507
2508 int deviceOn[NUM_AUDIO_DEVICES];
2509 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2510 deviceOn[i] = 0;
2511 }
2512
2513 if ((params & kBatteryDataSpeakerOn)
2514 && (params & kBatteryDataOtherAudioDeviceOn)) {
2515 deviceOn[SPEAKER_AND_OTHER] = 1;
2516 } else if (params & kBatteryDataSpeakerOn) {
2517 deviceOn[SPEAKER] = 1;
2518 } else {
2519 deviceOn[OTHER_AUDIO_DEVICE] = 1;
2520 }
2521
2522 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2523 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
2524
2525 if (mBatteryAudio.refCount > 0) { // if playing audio
2526 if (!deviceOn[i]) {
2527 mBatteryAudio.lastTime[i] += time;
2528 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2529 mBatteryAudio.lastTime[i] = 0;
2530 } else {
2531 mBatteryAudio.lastTime[i] = 0 - time;
2532 }
2533 }
2534
2535 mBatteryAudio.deviceOn[i] = deviceOn[i];
2536 }
2537 }
2538 return;
2539 }
2540
Marco Nelissenb7848f12014-12-04 08:57:56 -08002541 // an audio stream is started
Gloria Wang9ee159b2011-02-24 14:51:45 -08002542 if (params & kBatteryDataAudioFlingerStart) {
2543 // record the start time only if currently no other audio
2544 // is being played
2545 if (mBatteryAudio.refCount == 0) {
2546 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2547 if (mBatteryAudio.deviceOn[i]) {
2548 mBatteryAudio.lastTime[i] -= time;
2549 }
2550 }
2551 }
2552
2553 mBatteryAudio.refCount ++;
2554 return;
2555
2556 } else if (params & kBatteryDataAudioFlingerStop) {
2557 if (mBatteryAudio.refCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002558 ALOGW("Battery track warning: refCount is <= 0");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002559 return;
2560 }
2561
2562 // record the stop time only if currently this is the only
2563 // audio being played
2564 if (mBatteryAudio.refCount == 1) {
2565 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2566 if (mBatteryAudio.deviceOn[i]) {
2567 mBatteryAudio.lastTime[i] += time;
2568 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2569 mBatteryAudio.lastTime[i] = 0;
2570 }
2571 }
2572 }
2573
2574 mBatteryAudio.refCount --;
2575 return;
2576 }
2577
Andy Hung1afd0982016-11-08 16:13:44 -08002578 uid_t uid = IPCThreadState::self()->getCallingUid();
Gloria Wang7cf180c2011-02-19 18:37:57 -08002579 if (uid == AID_MEDIA) {
2580 return;
2581 }
2582 int index = mBatteryData.indexOfKey(uid);
Gloria Wang7cf180c2011-02-19 18:37:57 -08002583
2584 if (index < 0) { // create a new entry for this UID
2585 BatteryUsageInfo info;
2586 info.audioTotalTime = 0;
2587 info.videoTotalTime = 0;
2588 info.audioLastTime = 0;
2589 info.videoLastTime = 0;
2590 info.refCount = 0;
2591
Gloria Wang9ee159b2011-02-24 14:51:45 -08002592 if (mBatteryData.add(uid, info) == NO_MEMORY) {
Steve Block29357bc2012-01-06 19:20:56 +00002593 ALOGE("Battery track error: no memory for new app");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002594 return;
2595 }
Gloria Wang7cf180c2011-02-19 18:37:57 -08002596 }
2597
2598 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
2599
2600 if (params & kBatteryDataCodecStarted) {
2601 if (params & kBatteryDataTrackAudio) {
2602 info.audioLastTime -= time;
2603 info.refCount ++;
2604 }
2605 if (params & kBatteryDataTrackVideo) {
2606 info.videoLastTime -= time;
2607 info.refCount ++;
2608 }
2609 } else {
2610 if (info.refCount == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002611 ALOGW("Battery track warning: refCount is already 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002612 return;
2613 } else if (info.refCount < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00002614 ALOGE("Battery track error: refCount < 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002615 mBatteryData.removeItem(uid);
2616 return;
2617 }
2618
2619 if (params & kBatteryDataTrackAudio) {
2620 info.audioLastTime += time;
2621 info.refCount --;
2622 }
2623 if (params & kBatteryDataTrackVideo) {
2624 info.videoLastTime += time;
2625 info.refCount --;
2626 }
2627
2628 // no stream is being played by this UID
2629 if (info.refCount == 0) {
2630 info.audioTotalTime += info.audioLastTime;
2631 info.audioLastTime = 0;
2632 info.videoTotalTime += info.videoLastTime;
2633 info.videoLastTime = 0;
2634 }
2635 }
2636}
2637
Chong Zhange5b9b692017-05-11 11:44:56 -07002638status_t MediaPlayerService::BatteryTracker::pullBatteryData(Parcel* reply) {
Gloria Wang7cf180c2011-02-19 18:37:57 -08002639 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002640
2641 // audio output devices usage
2642 int32_t time = systemTime() / 1000000L; //in ms
2643 int32_t totalTime;
2644
2645 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2646 totalTime = mBatteryAudio.totalTime[i];
2647
2648 if (mBatteryAudio.deviceOn[i]
2649 && (mBatteryAudio.lastTime[i] != 0)) {
2650 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
2651 totalTime += tmpTime;
2652 }
2653
2654 reply->writeInt32(totalTime);
2655 // reset the total time
2656 mBatteryAudio.totalTime[i] = 0;
2657 }
2658
2659 // codec usage
Gloria Wang7cf180c2011-02-19 18:37:57 -08002660 BatteryUsageInfo info;
2661 int size = mBatteryData.size();
2662
2663 reply->writeInt32(size);
2664 int i = 0;
2665
2666 while (i < size) {
2667 info = mBatteryData.valueAt(i);
2668
2669 reply->writeInt32(mBatteryData.keyAt(i)); //UID
2670 reply->writeInt32(info.audioTotalTime);
2671 reply->writeInt32(info.videoTotalTime);
2672
2673 info.audioTotalTime = 0;
2674 info.videoTotalTime = 0;
2675
2676 // remove the UID entry where no stream is being played
2677 if (info.refCount <= 0) {
2678 mBatteryData.removeItemsAt(i);
2679 size --;
2680 i --;
2681 }
2682 i++;
2683 }
2684 return NO_ERROR;
2685}
nikoa64c8c72009-07-20 15:07:26 -07002686} // namespace android