blob: f3fc9248e50670fd190122748cda5714187135a8 [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
278 mBatteryAudio.refCount = 0;
279 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
280 mBatteryAudio.deviceOn[i] = 0;
281 mBatteryAudio.lastTime[i] = 0;
282 mBatteryAudio.totalTime[i] = 0;
283 }
284 // speaker is on by default
285 mBatteryAudio.deviceOn[SPEAKER] = 1;
John Grossman44a7e422012-06-21 17:29:24 -0700286
Chong Zhang0b30fd42014-07-23 14:46:05 -0700287 // reset battery stats
288 // if the mediaserver has crashed, battery stats could be left
289 // in bad state, reset the state upon service start.
Wei Jia3f273d12015-11-24 09:06:49 -0800290 BatteryNotifier::getInstance().noteResetVideo();
Chong Zhang0b30fd42014-07-23 14:46:05 -0700291
John Grossman44a7e422012-06-21 17:29:24 -0700292 MediaPlayerFactory::registerBuiltinFactories();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800293}
294
295MediaPlayerService::~MediaPlayerService()
296{
Steve Block3856b092011-10-20 11:56:00 +0100297 ALOGV("MediaPlayerService destroyed");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800298}
299
Svet Ganovbe71aa22015-04-28 12:06:02 -0700300sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(const String16 &opPackageName)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800301{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800302 pid_t pid = IPCThreadState::self()->getCallingPid();
Svet Ganovbe71aa22015-04-28 12:06:02 -0700303 sp<MediaRecorderClient> recorder = new MediaRecorderClient(this, pid, opPackageName);
Gloria Wangdac6a312009-10-29 15:46:37 -0700304 wp<MediaRecorderClient> w = recorder;
305 Mutex::Autolock lock(mLock);
306 mMediaRecorderClients.add(w);
Steve Block3856b092011-10-20 11:56:00 +0100307 ALOGV("Create new media recorder client from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800308 return recorder;
309}
310
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -0700311void MediaPlayerService::removeMediaRecorderClient(const wp<MediaRecorderClient>& client)
Gloria Wangdac6a312009-10-29 15:46:37 -0700312{
313 Mutex::Autolock lock(mLock);
314 mMediaRecorderClients.remove(client);
Steve Block3856b092011-10-20 11:56:00 +0100315 ALOGV("Delete media recorder client");
Gloria Wangdac6a312009-10-29 15:46:37 -0700316}
317
Glenn Kastenf37971f2012-02-03 11:06:53 -0800318sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800319{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800320 pid_t pid = IPCThreadState::self()->getCallingPid();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800321 sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
Steve Block3856b092011-10-20 11:56:00 +0100322 ALOGV("Create new media retriever from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800323 return retriever;
324}
325
Glenn Kastenf37971f2012-02-03 11:06:53 -0800326sp<IMediaPlayer> MediaPlayerService::create(const sp<IMediaPlayerClient>& client,
Glenn Kastend848eb42016-03-08 13:42:11 -0800327 audio_session_t audioSessionId)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800328{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800329 pid_t pid = IPCThreadState::self()->getCallingPid();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800330 int32_t connId = android_atomic_inc(&mNextConnId);
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700331
332 sp<Client> c = new Client(
333 this, pid, connId, client, audioSessionId,
334 IPCThreadState::self()->getCallingUid());
335
Steve Block3856b092011-10-20 11:56:00 +0100336 ALOGV("Create new client(%d) from pid %d, uid %d, ", connId, pid,
Dave Burked681bbb2011-08-30 14:39:17 +0100337 IPCThreadState::self()->getCallingUid());
338
339 wp<Client> w = c;
340 {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800341 Mutex::Autolock lock(mLock);
342 mClients.add(w);
343 }
Andreas Hubere2b10282010-11-23 11:41:34 -0800344 return c;
345}
346
Lajos Molnar1381d4b2014-08-07 15:18:35 -0700347sp<IMediaCodecList> MediaPlayerService::getCodecList() const {
348 return MediaCodecList::getLocalInstance();
349}
350
Marco Nelissen260e56c2016-01-28 21:41:25 +0000351sp<IOMX> MediaPlayerService::getOMX() {
Marco Nelissen1900e772016-02-02 16:12:16 -0800352 ALOGI("MediaPlayerService::getOMX");
Marco Nelissen260e56c2016-01-28 21:41:25 +0000353 Mutex::Autolock autoLock(mLock);
354
355 if (mOMX.get() == NULL) {
356 mOMX = new OMX;
357 }
358
359 return mOMX;
360}
361
Andreas Huber279dcd82013-01-30 10:41:25 -0800362sp<IHDCP> MediaPlayerService::makeHDCP(bool createEncryptionModule) {
363 return new HDCP(createEncryptionModule);
Andreas Huber59451f82012-09-18 10:36:32 -0700364}
365
Jeff Brown2013a542012-09-04 21:38:42 -0700366sp<IRemoteDisplay> MediaPlayerService::listenForRemoteDisplay(
Svet Ganovbe71aa22015-04-28 12:06:02 -0700367 const String16 &opPackageName,
Jeff Brown2013a542012-09-04 21:38:42 -0700368 const sp<IRemoteDisplayClient>& client, const String8& iface) {
Jeff Brownaba33d52012-09-07 17:38:58 -0700369 if (!checkPermission("android.permission.CONTROL_WIFI_DISPLAY")) {
370 return NULL;
371 }
372
Svet Ganovbe71aa22015-04-28 12:06:02 -0700373 return new RemoteDisplay(opPackageName, client, iface.string());
Jeff Brown2013a542012-09-04 21:38:42 -0700374}
375
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800376status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
377{
378 const size_t SIZE = 256;
379 char buffer[SIZE];
380 String8 result;
381
382 result.append(" AudioOutput\n");
383 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n",
384 mStreamType, mLeftVolume, mRightVolume);
385 result.append(buffer);
386 snprintf(buffer, 255, " msec per frame(%f), latency (%d)\n",
Eric Laurentdb354e52012-03-05 17:27:11 -0800387 mMsecsPerFrame, (mTrack != 0) ? mTrack->latency() : -1);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800388 result.append(buffer);
Eric Laurent2beeb502010-07-16 07:43:46 -0700389 snprintf(buffer, 255, " aux effect id(%d), send level (%f)\n",
390 mAuxEffectId, mSendLevel);
391 result.append(buffer);
392
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800393 ::write(fd, result.string(), result.size());
394 if (mTrack != 0) {
395 mTrack->dump(fd, args);
396 }
397 return NO_ERROR;
398}
399
Lajos Molnar6d339f12015-04-17 16:15:53 -0700400status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800401{
402 const size_t SIZE = 256;
403 char buffer[SIZE];
404 String8 result;
405 result.append(" Client\n");
406 snprintf(buffer, 255, " pid(%d), connId(%d), status(%d), looping(%s)\n",
407 mPid, mConnId, mStatus, mLoop?"true": "false");
408 result.append(buffer);
409 write(fd, result.string(), result.size());
Andreas Hubera0b1d4b2011-06-07 15:52:25 -0700410 if (mPlayer != NULL) {
411 mPlayer->dump(fd, args);
412 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800413 if (mAudioOutput != 0) {
414 mAudioOutput->dump(fd, args);
415 }
416 write(fd, "\n", 1);
417 return NO_ERROR;
418}
419
Marco Nelissenf09611f2015-02-13 14:12:42 -0800420/**
421 * The only arguments this understands right now are -c, -von and -voff,
422 * which are parsed by ALooperRoster::dump()
423 */
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800424status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
425{
426 const size_t SIZE = 256;
427 char buffer[SIZE];
428 String8 result;
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530429 SortedVector< sp<Client> > clients; //to serialise the mutex unlock & client destruction.
430 SortedVector< sp<MediaRecorderClient> > mediaRecorderClients;
431
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800432 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
433 snprintf(buffer, SIZE, "Permission Denial: "
434 "can't dump MediaPlayerService from pid=%d, uid=%d\n",
435 IPCThreadState::self()->getCallingPid(),
436 IPCThreadState::self()->getCallingUid());
437 result.append(buffer);
438 } else {
439 Mutex::Autolock lock(mLock);
440 for (int i = 0, n = mClients.size(); i < n; ++i) {
441 sp<Client> c = mClients[i].promote();
442 if (c != 0) c->dump(fd, args);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530443 clients.add(c);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800444 }
James Dongb9141222010-07-08 11:16:11 -0700445 if (mMediaRecorderClients.size() == 0) {
446 result.append(" No media recorder client\n\n");
447 } else {
448 for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
449 sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
James Donge579e282011-10-18 22:29:20 -0700450 if (c != 0) {
451 snprintf(buffer, 255, " MediaRecorderClient pid(%d)\n", c->mPid);
452 result.append(buffer);
453 write(fd, result.string(), result.size());
454 result = "\n";
455 c->dump(fd, args);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530456 mediaRecorderClients.add(c);
James Donge579e282011-10-18 22:29:20 -0700457 }
James Dongb9141222010-07-08 11:16:11 -0700458 }
Gloria Wangdac6a312009-10-29 15:46:37 -0700459 }
460
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800461 result.append(" Files opened and/or mapped:\n");
Marco Nelissenf09611f2015-02-13 14:12:42 -0800462 snprintf(buffer, SIZE, "/proc/%d/maps", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800463 FILE *f = fopen(buffer, "r");
464 if (f) {
465 while (!feof(f)) {
466 fgets(buffer, SIZE, f);
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700467 if (strstr(buffer, " /storage/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800468 strstr(buffer, " /system/sounds/") ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700469 strstr(buffer, " /data/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800470 strstr(buffer, " /system/media/")) {
471 result.append(" ");
472 result.append(buffer);
473 }
474 }
475 fclose(f);
476 } else {
477 result.append("couldn't open ");
478 result.append(buffer);
479 result.append("\n");
480 }
481
Marco Nelissenf09611f2015-02-13 14:12:42 -0800482 snprintf(buffer, SIZE, "/proc/%d/fd", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800483 DIR *d = opendir(buffer);
484 if (d) {
485 struct dirent *ent;
486 while((ent = readdir(d)) != NULL) {
487 if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
Marco Nelissenf09611f2015-02-13 14:12:42 -0800488 snprintf(buffer, SIZE, "/proc/%d/fd/%s", getpid(), ent->d_name);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800489 struct stat s;
490 if (lstat(buffer, &s) == 0) {
491 if ((s.st_mode & S_IFMT) == S_IFLNK) {
492 char linkto[256];
493 int len = readlink(buffer, linkto, sizeof(linkto));
494 if(len > 0) {
495 if(len > 255) {
496 linkto[252] = '.';
497 linkto[253] = '.';
498 linkto[254] = '.';
499 linkto[255] = 0;
500 } else {
501 linkto[len] = 0;
502 }
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700503 if (strstr(linkto, "/storage/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800504 strstr(linkto, "/system/sounds/") == linkto ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700505 strstr(linkto, "/data/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800506 strstr(linkto, "/system/media/") == linkto) {
507 result.append(" ");
508 result.append(buffer);
509 result.append(" -> ");
510 result.append(linkto);
511 result.append("\n");
512 }
513 }
514 } else {
515 result.append(" unexpected type for ");
516 result.append(buffer);
517 result.append("\n");
518 }
519 }
520 }
521 }
522 closedir(d);
523 } else {
524 result.append("couldn't open ");
525 result.append(buffer);
526 result.append("\n");
527 }
528
Marco Nelissenf09611f2015-02-13 14:12:42 -0800529 gLooperRoster.dump(fd, args);
530
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800531 bool dumpMem = false;
Andy Hung53541292016-04-13 16:48:51 -0700532 bool unreachableMemory = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800533 for (size_t i = 0; i < args.size(); i++) {
534 if (args[i] == String16("-m")) {
535 dumpMem = true;
Andy Hung53541292016-04-13 16:48:51 -0700536 } else if (args[i] == String16("--unreachable")) {
537 unreachableMemory = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800538 }
539 }
540 if (dumpMem) {
Andy Hung07b745e2016-05-23 16:21:07 -0700541 result.append("\nDumping memory:\n");
542 std::string s = dumpMemoryAddresses(100 /* limit */);
543 result.append(s.c_str(), s.size());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800544 }
Andy Hung53541292016-04-13 16:48:51 -0700545 if (unreachableMemory) {
546 result.append("\nDumping unreachable memory:\n");
547 // TODO - should limit be an argument parameter?
548 std::string s = GetUnreachableMemoryString(true /* contents */, 10000 /* limit */);
549 result.append(s.c_str(), s.size());
550 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800551 }
552 write(fd, result.string(), result.size());
553 return NO_ERROR;
554}
555
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -0700556void MediaPlayerService::removeClient(const wp<Client>& client)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800557{
558 Mutex::Autolock lock(mLock);
559 mClients.remove(client);
560}
561
Robert Shihee0a0e32016-08-16 16:50:54 -0700562bool MediaPlayerService::hasClient(wp<Client> client)
563{
564 Mutex::Autolock lock(mLock);
565 return mClients.indexOf(client) != NAME_NOT_FOUND;
566}
567
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700568MediaPlayerService::Client::Client(
569 const sp<MediaPlayerService>& service, pid_t pid,
570 int32_t connId, const sp<IMediaPlayerClient>& client,
Glenn Kastend848eb42016-03-08 13:42:11 -0800571 audio_session_t audioSessionId, uid_t uid)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800572{
Steve Block3856b092011-10-20 11:56:00 +0100573 ALOGV("Client(%d) constructor", connId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800574 mPid = pid;
575 mConnId = connId;
576 mService = service;
577 mClient = client;
578 mLoop = false;
579 mStatus = NO_INIT;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700580 mAudioSessionId = audioSessionId;
Andy Hung1afd0982016-11-08 16:13:44 -0800581 mUid = uid;
John Grossmanc795b642012-02-22 15:38:35 -0800582 mRetransmitEndpointValid = false;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700583 mAudioAttributes = NULL;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700584
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800585#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000586 ALOGD("create Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800587 mAntagonizer = new Antagonizer(notify, this);
588#endif
589}
590
591MediaPlayerService::Client::~Client()
592{
Steve Block3856b092011-10-20 11:56:00 +0100593 ALOGV("Client(%d) destructor pid = %d", mConnId, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800594 mAudioOutput.clear();
595 wp<Client> client(this);
596 disconnect();
597 mService->removeClient(client);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700598 if (mAudioAttributes != NULL) {
599 free(mAudioAttributes);
600 }
Pawin Vongmasa9c47c972017-02-08 04:09:38 -0800601 clearDeathNotifiers();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800602}
603
604void MediaPlayerService::Client::disconnect()
605{
Steve Block3856b092011-10-20 11:56:00 +0100606 ALOGV("disconnect(%d) from pid %d", mConnId, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800607 // grab local reference and clear main reference to prevent future
608 // access to object
609 sp<MediaPlayerBase> p;
610 {
611 Mutex::Autolock l(mLock);
612 p = mPlayer;
beanzdcfefde2012-11-05 09:51:43 +0800613 mClient.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800614 }
Andreas Huber20111aa2009-07-14 16:56:47 -0700615
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800616 mPlayer.clear();
617
618 // clear the notification to prevent callbacks to dead client
619 // and reset the player. We assume the player will serialize
620 // access to itself if necessary.
621 if (p != 0) {
622 p->setNotifyCallback(0, 0);
623#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000624 ALOGD("kill Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800625 mAntagonizer->kill();
626#endif
627 p->reset();
628 }
629
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700630 disconnectNativeWindow();
631
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800632 IPCThreadState::self()->flushCommands();
633}
634
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800635sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
636{
637 // determine if we have the right player type
638 sp<MediaPlayerBase> p = mPlayer;
639 if ((p != NULL) && (p->playerType() != playerType)) {
Steve Block3856b092011-10-20 11:56:00 +0100640 ALOGV("delete player");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800641 p.clear();
642 }
643 if (p == NULL) {
Ronghua Wu68845c12015-07-21 09:50:48 -0700644 p = MediaPlayerFactory::createPlayer(playerType, this, notify, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800645 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700646
Jason Simmonsdb29e522011-08-12 13:46:55 -0700647 if (p != NULL) {
Andy Hung1afd0982016-11-08 16:13:44 -0800648 p->setUID(mUid);
Jason Simmonsdb29e522011-08-12 13:46:55 -0700649 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700650
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800651 return p;
652}
653
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700654MediaPlayerService::Client::ServiceDeathNotifier::ServiceDeathNotifier(
655 const sp<IBinder>& service,
656 const sp<MediaPlayerBase>& listener,
657 int which) {
658 mService = service;
Pawin Vongmasa9c47c972017-02-08 04:09:38 -0800659 mOmx = nullptr;
660 mListener = listener;
661 mWhich = which;
662}
663
664MediaPlayerService::Client::ServiceDeathNotifier::ServiceDeathNotifier(
665 const sp<IOmx>& omx,
666 const sp<MediaPlayerBase>& listener,
667 int which) {
668 mService = nullptr;
669 mOmx = omx;
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700670 mListener = listener;
671 mWhich = which;
672}
673
674MediaPlayerService::Client::ServiceDeathNotifier::~ServiceDeathNotifier() {
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700675}
676
677void MediaPlayerService::Client::ServiceDeathNotifier::binderDied(const wp<IBinder>& /*who*/) {
678 sp<MediaPlayerBase> listener = mListener.promote();
679 if (listener != NULL) {
680 listener->sendEvent(MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED, mWhich);
681 } else {
682 ALOGW("listener for process %d death is gone", mWhich);
683 }
684}
685
Pawin Vongmasa9c47c972017-02-08 04:09:38 -0800686void MediaPlayerService::Client::ServiceDeathNotifier::serviceDied(
687 uint64_t /* cookie */,
688 const wp<::android::hidl::base::V1_0::IBase>& /* who */) {
689 sp<MediaPlayerBase> listener = mListener.promote();
690 if (listener != NULL) {
691 listener->sendEvent(MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED, mWhich);
692 } else {
693 ALOGW("listener for process %d death is gone", mWhich);
694 }
695}
696
697void MediaPlayerService::Client::ServiceDeathNotifier::unlinkToDeath() {
698 if (mService != nullptr) {
699 mService->unlinkToDeath(this);
700 mService = nullptr;
701 } else if (mOmx != nullptr) {
702 mOmx->unlinkToDeath(this);
703 mOmx = nullptr;
704 }
705}
706
707void MediaPlayerService::Client::clearDeathNotifiers() {
708 if (mExtractorDeathListener != nullptr) {
709 mExtractorDeathListener->unlinkToDeath();
710 mExtractorDeathListener = nullptr;
711 }
712 if (mCodecDeathListener != nullptr) {
713 mCodecDeathListener->unlinkToDeath();
714 mCodecDeathListener = nullptr;
715 }
716}
717
John Grossmanc795b642012-02-22 15:38:35 -0800718sp<MediaPlayerBase> MediaPlayerService::Client::setDataSource_pre(
719 player_type playerType)
720{
721 ALOGV("player type = %d", playerType);
Pawin Vongmasa9c47c972017-02-08 04:09:38 -0800722 clearDeathNotifiers();
John Grossmanc795b642012-02-22 15:38:35 -0800723
724 // create the right type of player
725 sp<MediaPlayerBase> p = createPlayer(playerType);
726 if (p == NULL) {
727 return p;
728 }
729
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700730 sp<IServiceManager> sm = defaultServiceManager();
731 sp<IBinder> binder = sm->getService(String16("media.extractor"));
Marco Nelissen1b5a7ee2016-09-30 13:54:30 -0700732 if (binder == NULL) {
733 ALOGE("extractor service not available");
734 return NULL;
735 }
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700736 mExtractorDeathListener = new ServiceDeathNotifier(binder, p, MEDIAEXTRACTOR_PROCESS_DEATH);
737 binder->linkToDeath(mExtractorDeathListener);
738
Pawin Vongmasa9c47c972017-02-08 04:09:38 -0800739 int32_t trebleOmx = property_get_int32("persist.media.treble_omx", -1);
740 if ((trebleOmx == 1) || ((trebleOmx == -1) &&
Steven Moreland7e0c3c32017-02-22 21:15:02 -0800741 property_get_bool("persist.hal.binderization", 0))) {
Pawin Vongmasa9c47c972017-02-08 04:09:38 -0800742 // Treble IOmx
743 sp<IOmx> omx = IOmx::getService();
744 if (omx == nullptr) {
745 ALOGE("Treble IOmx not available");
746 return NULL;
747 }
748 mCodecDeathListener = new ServiceDeathNotifier(omx, p, MEDIACODEC_PROCESS_DEATH);
749 omx->linkToDeath(mCodecDeathListener, 0);
750 } else {
751 // Legacy IOMX
752 binder = sm->getService(String16("media.codec"));
753 if (binder == NULL) {
754 ALOGE("codec service not available");
755 return NULL;
756 }
757 mCodecDeathListener = new ServiceDeathNotifier(binder, p, MEDIACODEC_PROCESS_DEATH);
758 binder->linkToDeath(mCodecDeathListener);
Marco Nelissen1b5a7ee2016-09-30 13:54:30 -0700759 }
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700760
John Grossmanc795b642012-02-22 15:38:35 -0800761 if (!p->hardwareOutput()) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -0700762 Mutex::Autolock l(mLock);
Marco Nelissend457c972014-02-11 08:47:07 -0800763 mAudioOutput = new AudioOutput(mAudioSessionId, IPCThreadState::self()->getCallingUid(),
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700764 mPid, mAudioAttributes);
John Grossmanc795b642012-02-22 15:38:35 -0800765 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
766 }
767
768 return p;
769}
770
771void MediaPlayerService::Client::setDataSource_post(
772 const sp<MediaPlayerBase>& p,
773 status_t status)
774{
775 ALOGV(" setDataSource");
776 mStatus = status;
777 if (mStatus != OK) {
778 ALOGE(" error: %d", mStatus);
779 return;
780 }
781
782 // Set the re-transmission endpoint if one was chosen.
783 if (mRetransmitEndpointValid) {
784 mStatus = p->setRetransmitEndpoint(&mRetransmitEndpoint);
785 if (mStatus != NO_ERROR) {
786 ALOGE("setRetransmitEndpoint error: %d", mStatus);
787 }
788 }
789
790 if (mStatus == OK) {
791 mPlayer = p;
792 }
793}
794
Andreas Huber2db84552010-01-28 11:19:57 -0800795status_t MediaPlayerService::Client::setDataSource(
Andreas Huber1b86fe02014-01-29 11:13:26 -0800796 const sp<IMediaHTTPService> &httpService,
797 const char *url,
798 const KeyedVector<String8, String8> *headers)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800799{
Steve Block3856b092011-10-20 11:56:00 +0100800 ALOGV("setDataSource(%s)", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800801 if (url == NULL)
802 return UNKNOWN_ERROR;
803
Dave Burked681bbb2011-08-30 14:39:17 +0100804 if ((strncmp(url, "http://", 7) == 0) ||
805 (strncmp(url, "https://", 8) == 0) ||
806 (strncmp(url, "rtsp://", 7) == 0)) {
807 if (!checkPermission("android.permission.INTERNET")) {
808 return PERMISSION_DENIED;
809 }
810 }
811
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800812 if (strncmp(url, "content://", 10) == 0) {
813 // get a filedescriptor for the content Uri and
814 // pass it to the setDataSource(fd) method
815
816 String16 url16(url);
817 int fd = android::openContentProviderFile(url16);
818 if (fd < 0)
819 {
Steve Block29357bc2012-01-06 19:20:56 +0000820 ALOGE("Couldn't open fd for %s", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800821 return UNKNOWN_ERROR;
822 }
823 setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
824 close(fd);
825 return mStatus;
826 } else {
John Grossman44a7e422012-06-21 17:29:24 -0700827 player_type playerType = MediaPlayerFactory::getPlayerType(this, url);
John Grossmanc795b642012-02-22 15:38:35 -0800828 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
829 if (p == NULL) {
830 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800831 }
832
Andreas Huber1b86fe02014-01-29 11:13:26 -0800833 setDataSource_post(p, p->setDataSource(httpService, url, headers));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800834 return mStatus;
835 }
836}
837
838status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
839{
Marco Nelissen83b0fd92015-09-16 13:48:07 -0700840 ALOGV("setDataSource fd=%d (%s), offset=%lld, length=%lld",
841 fd, nameForFd(fd).c_str(), (long long) offset, (long long) length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800842 struct stat sb;
843 int ret = fstat(fd, &sb);
844 if (ret != 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000845 ALOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800846 return UNKNOWN_ERROR;
847 }
848
Andy Hung833b4752016-04-04 17:15:48 -0700849 ALOGV("st_dev = %llu", static_cast<unsigned long long>(sb.st_dev));
Steve Block3856b092011-10-20 11:56:00 +0100850 ALOGV("st_mode = %u", sb.st_mode);
Mark Salyzyn77342f72014-06-18 16:31:32 -0700851 ALOGV("st_uid = %lu", static_cast<unsigned long>(sb.st_uid));
852 ALOGV("st_gid = %lu", static_cast<unsigned long>(sb.st_gid));
Andy Hung833b4752016-04-04 17:15:48 -0700853 ALOGV("st_size = %llu", static_cast<unsigned long long>(sb.st_size));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800854
855 if (offset >= sb.st_size) {
Steve Block29357bc2012-01-06 19:20:56 +0000856 ALOGE("offset error");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800857 return UNKNOWN_ERROR;
858 }
859 if (offset + length > sb.st_size) {
860 length = sb.st_size - offset;
Andy Hung833b4752016-04-04 17:15:48 -0700861 ALOGV("calculated length = %lld", (long long)length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800862 }
863
John Grossman44a7e422012-06-21 17:29:24 -0700864 player_type playerType = MediaPlayerFactory::getPlayerType(this,
865 fd,
866 offset,
867 length);
John Grossmanc795b642012-02-22 15:38:35 -0800868 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
869 if (p == NULL) {
870 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800871 }
872
873 // now set data source
John Grossmanc795b642012-02-22 15:38:35 -0800874 setDataSource_post(p, p->setDataSource(fd, offset, length));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800875 return mStatus;
876}
877
Andreas Hubere2b10282010-11-23 11:41:34 -0800878status_t MediaPlayerService::Client::setDataSource(
879 const sp<IStreamSource> &source) {
880 // create the right type of player
John Grossman44a7e422012-06-21 17:29:24 -0700881 player_type playerType = MediaPlayerFactory::getPlayerType(this, source);
John Grossmanc795b642012-02-22 15:38:35 -0800882 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
Andreas Hubere2b10282010-11-23 11:41:34 -0800883 if (p == NULL) {
884 return NO_INIT;
885 }
886
Andreas Hubere2b10282010-11-23 11:41:34 -0800887 // now set data source
John Grossmanc795b642012-02-22 15:38:35 -0800888 setDataSource_post(p, p->setDataSource(source));
Andreas Hubere2b10282010-11-23 11:41:34 -0800889 return mStatus;
890}
891
Chris Watkins99f31602015-03-20 13:06:33 -0700892status_t MediaPlayerService::Client::setDataSource(
893 const sp<IDataSource> &source) {
894 sp<DataSource> dataSource = DataSource::CreateFromIDataSource(source);
895 player_type playerType = MediaPlayerFactory::getPlayerType(this, dataSource);
896 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
897 if (p == NULL) {
898 return NO_INIT;
899 }
900 // now set data source
901 setDataSource_post(p, p->setDataSource(dataSource));
902 return mStatus;
903}
904
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700905void MediaPlayerService::Client::disconnectNativeWindow() {
906 if (mConnectedWindow != NULL) {
Chong Zhang181fd9b2017-02-16 15:53:03 -0800907 status_t err = nativeWindowDisconnect(
908 mConnectedWindow.get(), "disconnectNativeWindow");
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700909
910 if (err != OK) {
Chong Zhang181fd9b2017-02-16 15:53:03 -0800911 ALOGW("nativeWindowDisconnect returned an error: %s (%d)",
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700912 strerror(-err), err);
913 }
914 }
915 mConnectedWindow.clear();
916}
917
Glenn Kasten11731182011-02-08 17:26:17 -0800918status_t MediaPlayerService::Client::setVideoSurfaceTexture(
Andy McFadden484566c2012-12-18 09:46:54 -0800919 const sp<IGraphicBufferProducer>& bufferProducer)
Glenn Kasten11731182011-02-08 17:26:17 -0800920{
Andy McFadden484566c2012-12-18 09:46:54 -0800921 ALOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, bufferProducer.get());
Glenn Kasten11731182011-02-08 17:26:17 -0800922 sp<MediaPlayerBase> p = getPlayer();
923 if (p == 0) return UNKNOWN_ERROR;
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700924
Marco Nelissenf8880202014-11-14 07:58:25 -0800925 sp<IBinder> binder(IInterface::asBinder(bufferProducer));
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700926 if (mConnectedWindowBinder == binder) {
927 return OK;
928 }
929
930 sp<ANativeWindow> anw;
Andy McFadden484566c2012-12-18 09:46:54 -0800931 if (bufferProducer != NULL) {
Marco Nelissenee08f7e2013-09-16 13:30:01 -0700932 anw = new Surface(bufferProducer, true /* controlledByApp */);
Chong Zhang181fd9b2017-02-16 15:53:03 -0800933 status_t err = nativeWindowConnect(anw.get(), "setVideoSurfaceTexture");
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700934
935 if (err != OK) {
Steve Block29357bc2012-01-06 19:20:56 +0000936 ALOGE("setVideoSurfaceTexture failed: %d", err);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700937 // Note that we must do the reset before disconnecting from the ANW.
938 // Otherwise queue/dequeue calls could be made on the disconnected
939 // ANW, which may result in errors.
940 reset();
941
942 disconnectNativeWindow();
943
944 return err;
945 }
946 }
947
Andy McFadden484566c2012-12-18 09:46:54 -0800948 // Note that we must set the player's new GraphicBufferProducer before
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700949 // disconnecting the old one. Otherwise queue/dequeue calls could be made
950 // on the disconnected ANW, which may result in errors.
Andy McFadden484566c2012-12-18 09:46:54 -0800951 status_t err = p->setVideoSurfaceTexture(bufferProducer);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700952
953 disconnectNativeWindow();
954
955 mConnectedWindow = anw;
956
957 if (err == OK) {
958 mConnectedWindowBinder = binder;
959 } else {
960 disconnectNativeWindow();
961 }
962
963 return err;
Glenn Kasten11731182011-02-08 17:26:17 -0800964}
965
Nicolas Catania1d187f12009-05-12 23:25:55 -0700966status_t MediaPlayerService::Client::invoke(const Parcel& request,
967 Parcel *reply)
968{
969 sp<MediaPlayerBase> p = getPlayer();
970 if (p == NULL) return UNKNOWN_ERROR;
971 return p->invoke(request, reply);
972}
973
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700974// This call doesn't need to access the native player.
975status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
976{
977 status_t status;
nikoa64c8c72009-07-20 15:07:26 -0700978 media::Metadata::Filter allow, drop;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700979
Nicolas Catania48290382009-07-10 13:53:06 -0700980 if (unmarshallFilter(filter, &allow, &status) &&
981 unmarshallFilter(filter, &drop, &status)) {
982 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700983
984 mMetadataAllow = allow;
985 mMetadataDrop = drop;
986 }
987 return status;
988}
989
Nicolas Catania48290382009-07-10 13:53:06 -0700990status_t MediaPlayerService::Client::getMetadata(
Mark Salyzyn77342f72014-06-18 16:31:32 -0700991 bool update_only, bool /*apply_filter*/, Parcel *reply)
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700992{
nikoa64c8c72009-07-20 15:07:26 -0700993 sp<MediaPlayerBase> player = getPlayer();
994 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania48290382009-07-10 13:53:06 -0700995
nikod608a812009-07-16 16:39:53 -0700996 status_t status;
997 // Placeholder for the return code, updated by the caller.
998 reply->writeInt32(-1);
999
nikoa64c8c72009-07-20 15:07:26 -07001000 media::Metadata::Filter ids;
Nicolas Catania48290382009-07-10 13:53:06 -07001001
1002 // We don't block notifications while we fetch the data. We clear
1003 // mMetadataUpdated first so we don't lose notifications happening
1004 // during the rest of this call.
1005 {
1006 Mutex::Autolock lock(mLock);
1007 if (update_only) {
nikod608a812009-07-16 16:39:53 -07001008 ids = mMetadataUpdated;
Nicolas Catania48290382009-07-10 13:53:06 -07001009 }
1010 mMetadataUpdated.clear();
1011 }
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001012
nikoa64c8c72009-07-20 15:07:26 -07001013 media::Metadata metadata(reply);
Nicolas Catania48290382009-07-10 13:53:06 -07001014
nikoa64c8c72009-07-20 15:07:26 -07001015 metadata.appendHeader();
1016 status = player->getMetadata(ids, reply);
nikod608a812009-07-16 16:39:53 -07001017
1018 if (status != OK) {
nikoa64c8c72009-07-20 15:07:26 -07001019 metadata.resetParcel();
Steve Block29357bc2012-01-06 19:20:56 +00001020 ALOGE("getMetadata failed %d", status);
nikod608a812009-07-16 16:39:53 -07001021 return status;
1022 }
1023
1024 // FIXME: Implement filtering on the result. Not critical since
1025 // filtering takes place on the update notifications already. This
1026 // would be when all the metadata are fetch and a filter is set.
1027
nikod608a812009-07-16 16:39:53 -07001028 // Everything is fine, update the metadata length.
nikoa64c8c72009-07-20 15:07:26 -07001029 metadata.updateLength();
nikod608a812009-07-16 16:39:53 -07001030 return OK;
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001031}
1032
Wei Jiad399e7e2016-10-26 15:49:11 -07001033status_t MediaPlayerService::Client::setBufferingSettings(
1034 const BufferingSettings& buffering)
1035{
Wei Jiadc6f3402017-01-09 15:04:18 -08001036 ALOGV("[%d] setBufferingSettings{%s}",
1037 mConnId, buffering.toString().string());
Wei Jiad399e7e2016-10-26 15:49:11 -07001038 sp<MediaPlayerBase> p = getPlayer();
1039 if (p == 0) return UNKNOWN_ERROR;
1040 return p->setBufferingSettings(buffering);
1041}
1042
1043status_t MediaPlayerService::Client::getDefaultBufferingSettings(
1044 BufferingSettings* buffering /* nonnull */)
1045{
1046 sp<MediaPlayerBase> p = getPlayer();
1047 // TODO: create mPlayer on demand.
1048 if (p == 0) return UNKNOWN_ERROR;
1049 status_t ret = p->getDefaultBufferingSettings(buffering);
1050 if (ret == NO_ERROR) {
Wei Jiadc6f3402017-01-09 15:04:18 -08001051 ALOGV("[%d] getDefaultBufferingSettings{%s}",
1052 mConnId, buffering->toString().string());
Wei Jiad399e7e2016-10-26 15:49:11 -07001053 } else {
1054 ALOGV("[%d] getDefaultBufferingSettings returned %d", mConnId, ret);
1055 }
1056 return ret;
1057}
1058
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001059status_t MediaPlayerService::Client::prepareAsync()
1060{
Steve Block3856b092011-10-20 11:56:00 +01001061 ALOGV("[%d] prepareAsync", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001062 sp<MediaPlayerBase> p = getPlayer();
1063 if (p == 0) return UNKNOWN_ERROR;
1064 status_t ret = p->prepareAsync();
1065#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +00001066 ALOGD("start Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001067 if (ret == NO_ERROR) mAntagonizer->start();
1068#endif
1069 return ret;
1070}
1071
1072status_t MediaPlayerService::Client::start()
1073{
Steve Block3856b092011-10-20 11:56:00 +01001074 ALOGV("[%d] start", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001075 sp<MediaPlayerBase> p = getPlayer();
1076 if (p == 0) return UNKNOWN_ERROR;
1077 p->setLooping(mLoop);
1078 return p->start();
1079}
1080
1081status_t MediaPlayerService::Client::stop()
1082{
Steve Block3856b092011-10-20 11:56:00 +01001083 ALOGV("[%d] stop", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001084 sp<MediaPlayerBase> p = getPlayer();
1085 if (p == 0) return UNKNOWN_ERROR;
1086 return p->stop();
1087}
1088
1089status_t MediaPlayerService::Client::pause()
1090{
Steve Block3856b092011-10-20 11:56:00 +01001091 ALOGV("[%d] pause", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001092 sp<MediaPlayerBase> p = getPlayer();
1093 if (p == 0) return UNKNOWN_ERROR;
1094 return p->pause();
1095}
1096
1097status_t MediaPlayerService::Client::isPlaying(bool* state)
1098{
1099 *state = false;
1100 sp<MediaPlayerBase> p = getPlayer();
1101 if (p == 0) return UNKNOWN_ERROR;
1102 *state = p->isPlaying();
Steve Block3856b092011-10-20 11:56:00 +01001103 ALOGV("[%d] isPlaying: %d", mConnId, *state);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001104 return NO_ERROR;
1105}
1106
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001107status_t MediaPlayerService::Client::setPlaybackSettings(const AudioPlaybackRate& rate)
Wei Jia98160162015-02-04 17:01:11 -08001108{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001109 ALOGV("[%d] setPlaybackSettings(%f, %f, %d, %d)",
1110 mConnId, rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Wei Jia98160162015-02-04 17:01:11 -08001111 sp<MediaPlayerBase> p = getPlayer();
1112 if (p == 0) return UNKNOWN_ERROR;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001113 return p->setPlaybackSettings(rate);
1114}
1115
1116status_t MediaPlayerService::Client::getPlaybackSettings(AudioPlaybackRate* rate /* nonnull */)
1117{
1118 sp<MediaPlayerBase> p = getPlayer();
1119 if (p == 0) return UNKNOWN_ERROR;
1120 status_t ret = p->getPlaybackSettings(rate);
1121 if (ret == NO_ERROR) {
1122 ALOGV("[%d] getPlaybackSettings(%f, %f, %d, %d)",
1123 mConnId, rate->mSpeed, rate->mPitch, rate->mFallbackMode, rate->mStretchMode);
1124 } else {
1125 ALOGV("[%d] getPlaybackSettings returned %d", mConnId, ret);
1126 }
1127 return ret;
1128}
1129
1130status_t MediaPlayerService::Client::setSyncSettings(
1131 const AVSyncSettings& sync, float videoFpsHint)
1132{
1133 ALOGV("[%d] setSyncSettings(%u, %u, %f, %f)",
1134 mConnId, sync.mSource, sync.mAudioAdjustMode, sync.mTolerance, videoFpsHint);
1135 sp<MediaPlayerBase> p = getPlayer();
1136 if (p == 0) return UNKNOWN_ERROR;
1137 return p->setSyncSettings(sync, videoFpsHint);
1138}
1139
1140status_t MediaPlayerService::Client::getSyncSettings(
1141 AVSyncSettings* sync /* nonnull */, float* videoFps /* nonnull */)
1142{
1143 sp<MediaPlayerBase> p = getPlayer();
1144 if (p == 0) return UNKNOWN_ERROR;
1145 status_t ret = p->getSyncSettings(sync, videoFps);
1146 if (ret == NO_ERROR) {
1147 ALOGV("[%d] getSyncSettings(%u, %u, %f, %f)",
1148 mConnId, sync->mSource, sync->mAudioAdjustMode, sync->mTolerance, *videoFps);
1149 } else {
1150 ALOGV("[%d] getSyncSettings returned %d", mConnId, ret);
1151 }
1152 return ret;
Wei Jia98160162015-02-04 17:01:11 -08001153}
1154
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001155status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
1156{
Steve Block3856b092011-10-20 11:56:00 +01001157 ALOGV("getCurrentPosition");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001158 sp<MediaPlayerBase> p = getPlayer();
1159 if (p == 0) return UNKNOWN_ERROR;
1160 status_t ret = p->getCurrentPosition(msec);
1161 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001162 ALOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001163 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001164 ALOGE("getCurrentPosition returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001165 }
1166 return ret;
1167}
1168
1169status_t MediaPlayerService::Client::getDuration(int *msec)
1170{
Steve Block3856b092011-10-20 11:56:00 +01001171 ALOGV("getDuration");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001172 sp<MediaPlayerBase> p = getPlayer();
1173 if (p == 0) return UNKNOWN_ERROR;
1174 status_t ret = p->getDuration(msec);
1175 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001176 ALOGV("[%d] getDuration = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001177 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001178 ALOGE("getDuration returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001179 }
1180 return ret;
1181}
1182
Marco Nelissen6b74d672012-02-28 16:07:44 -08001183status_t MediaPlayerService::Client::setNextPlayer(const sp<IMediaPlayer>& player) {
1184 ALOGV("setNextPlayer");
1185 Mutex::Autolock l(mLock);
1186 sp<Client> c = static_cast<Client*>(player.get());
Wei Jia28284122016-08-30 13:49:06 -07001187 if (c != NULL && !mService->hasClient(c)) {
Robert Shihee0a0e32016-08-16 16:50:54 -07001188 return BAD_VALUE;
1189 }
1190
Marco Nelissen6b74d672012-02-28 16:07:44 -08001191 mNextClient = c;
John Grossman5f7e55e2012-08-24 14:47:25 -07001192
1193 if (c != NULL) {
1194 if (mAudioOutput != NULL) {
1195 mAudioOutput->setNextOutput(c->mAudioOutput);
1196 } else if ((mPlayer != NULL) && !mPlayer->hardwareOutput()) {
1197 ALOGE("no current audio output");
1198 }
1199
1200 if ((mPlayer != NULL) && (mNextClient->getPlayer() != NULL)) {
1201 mPlayer->setNextPlayer(mNextClient->getPlayer());
1202 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001203 }
John Grossman5f7e55e2012-08-24 14:47:25 -07001204
Marco Nelissen6b74d672012-02-28 16:07:44 -08001205 return OK;
1206}
1207
Andy Hung9fc8b5c2017-01-24 13:36:48 -08001208VolumeShaper::Status MediaPlayerService::Client::applyVolumeShaper(
1209 const sp<VolumeShaper::Configuration>& configuration,
1210 const sp<VolumeShaper::Operation>& operation) {
1211 // for hardware output, call player instead
1212 ALOGV("Client::applyVolumeShaper(%p)", this);
1213 sp<MediaPlayerBase> p = getPlayer();
1214 {
1215 Mutex::Autolock l(mLock);
1216 if (p != 0 && p->hardwareOutput()) {
1217 // TODO: investigate internal implementation
1218 return VolumeShaper::Status(INVALID_OPERATION);
1219 }
1220 if (mAudioOutput.get() != nullptr) {
1221 return mAudioOutput->applyVolumeShaper(configuration, operation);
1222 }
1223 }
1224 return VolumeShaper::Status(INVALID_OPERATION);
1225}
1226
1227sp<VolumeShaper::State> MediaPlayerService::Client::getVolumeShaperState(int id) {
1228 // for hardware output, call player instead
1229 ALOGV("Client::getVolumeShaperState(%p)", this);
1230 sp<MediaPlayerBase> p = getPlayer();
1231 {
1232 Mutex::Autolock l(mLock);
1233 if (p != 0 && p->hardwareOutput()) {
1234 // TODO: investigate internal implementation.
1235 return nullptr;
1236 }
1237 if (mAudioOutput.get() != nullptr) {
1238 return mAudioOutput->getVolumeShaperState(id);
1239 }
1240 }
1241 return nullptr;
1242}
1243
Wei Jiac5de0912016-11-18 10:22:14 -08001244status_t MediaPlayerService::Client::seekTo(int msec, MediaPlayerSeekMode mode)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001245{
Wei Jiac5de0912016-11-18 10:22:14 -08001246 ALOGV("[%d] seekTo(%d, %d)", mConnId, msec, mode);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001247 sp<MediaPlayerBase> p = getPlayer();
1248 if (p == 0) return UNKNOWN_ERROR;
Wei Jiac5de0912016-11-18 10:22:14 -08001249 return p->seekTo(msec, mode);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001250}
1251
1252status_t MediaPlayerService::Client::reset()
1253{
Steve Block3856b092011-10-20 11:56:00 +01001254 ALOGV("[%d] reset", mConnId);
John Grossmanc795b642012-02-22 15:38:35 -08001255 mRetransmitEndpointValid = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001256 sp<MediaPlayerBase> p = getPlayer();
1257 if (p == 0) return UNKNOWN_ERROR;
1258 return p->reset();
1259}
1260
Glenn Kastenfff6d712012-01-12 16:38:12 -08001261status_t MediaPlayerService::Client::setAudioStreamType(audio_stream_type_t type)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001262{
Steve Block3856b092011-10-20 11:56:00 +01001263 ALOGV("[%d] setAudioStreamType(%d)", mConnId, type);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001264 // TODO: for hardware output, call player instead
1265 Mutex::Autolock l(mLock);
1266 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1267 return NO_ERROR;
1268}
1269
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001270status_t MediaPlayerService::Client::setAudioAttributes_l(const Parcel &parcel)
1271{
1272 if (mAudioAttributes != NULL) { free(mAudioAttributes); }
1273 mAudioAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001274 if (mAudioAttributes == NULL) {
1275 return NO_MEMORY;
1276 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001277 unmarshallAudioAttributes(parcel, mAudioAttributes);
1278
1279 ALOGV("setAudioAttributes_l() usage=%d content=%d flags=0x%x tags=%s",
1280 mAudioAttributes->usage, mAudioAttributes->content_type, mAudioAttributes->flags,
1281 mAudioAttributes->tags);
1282
1283 if (mAudioOutput != 0) {
1284 mAudioOutput->setAudioAttributes(mAudioAttributes);
1285 }
1286 return NO_ERROR;
1287}
1288
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001289status_t MediaPlayerService::Client::setLooping(int loop)
1290{
Steve Block3856b092011-10-20 11:56:00 +01001291 ALOGV("[%d] setLooping(%d)", mConnId, loop);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001292 mLoop = loop;
1293 sp<MediaPlayerBase> p = getPlayer();
1294 if (p != 0) return p->setLooping(loop);
1295 return NO_ERROR;
1296}
1297
1298status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1299{
Steve Block3856b092011-10-20 11:56:00 +01001300 ALOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
John Grossman761defc2012-02-09 15:09:05 -08001301
1302 // for hardware output, call player instead
1303 sp<MediaPlayerBase> p = getPlayer();
1304 {
1305 Mutex::Autolock l(mLock);
1306 if (p != 0 && p->hardwareOutput()) {
1307 MediaPlayerHWInterface* hwp =
1308 reinterpret_cast<MediaPlayerHWInterface*>(p.get());
1309 return hwp->setVolume(leftVolume, rightVolume);
1310 } else {
1311 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1312 return NO_ERROR;
1313 }
1314 }
1315
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001316 return NO_ERROR;
1317}
1318
Eric Laurent2beeb502010-07-16 07:43:46 -07001319status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1320{
Steve Block3856b092011-10-20 11:56:00 +01001321 ALOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
Eric Laurent2beeb502010-07-16 07:43:46 -07001322 Mutex::Autolock l(mLock);
1323 if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1324 return NO_ERROR;
1325}
1326
1327status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1328{
Steve Block3856b092011-10-20 11:56:00 +01001329 ALOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
Eric Laurent2beeb502010-07-16 07:43:46 -07001330 Mutex::Autolock l(mLock);
1331 if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1332 return NO_ERROR;
1333}
Nicolas Catania48290382009-07-10 13:53:06 -07001334
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001335status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
Steve Block3856b092011-10-20 11:56:00 +01001336 ALOGV("[%d] setParameter(%d)", mConnId, key);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001337 switch (key) {
1338 case KEY_PARAMETER_AUDIO_ATTRIBUTES:
1339 {
1340 Mutex::Autolock l(mLock);
1341 return setAudioAttributes_l(request);
1342 }
1343 default:
1344 sp<MediaPlayerBase> p = getPlayer();
1345 if (p == 0) { return UNKNOWN_ERROR; }
1346 return p->setParameter(key, request);
1347 }
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001348}
1349
1350status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
Steve Block3856b092011-10-20 11:56:00 +01001351 ALOGV("[%d] getParameter(%d)", mConnId, key);
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001352 sp<MediaPlayerBase> p = getPlayer();
1353 if (p == 0) return UNKNOWN_ERROR;
1354 return p->getParameter(key, reply);
1355}
1356
John Grossmanc795b642012-02-22 15:38:35 -08001357status_t MediaPlayerService::Client::setRetransmitEndpoint(
1358 const struct sockaddr_in* endpoint) {
1359
1360 if (NULL != endpoint) {
1361 uint32_t a = ntohl(endpoint->sin_addr.s_addr);
1362 uint16_t p = ntohs(endpoint->sin_port);
1363 ALOGV("[%d] setRetransmitEndpoint(%u.%u.%u.%u:%hu)", mConnId,
1364 (a >> 24), (a >> 16) & 0xFF, (a >> 8) & 0xFF, (a & 0xFF), p);
1365 } else {
1366 ALOGV("[%d] setRetransmitEndpoint = <none>", mConnId);
1367 }
1368
1369 sp<MediaPlayerBase> p = getPlayer();
1370
1371 // Right now, the only valid time to set a retransmit endpoint is before
1372 // player selection has been made (since the presence or absence of a
1373 // retransmit endpoint is going to determine which player is selected during
1374 // setDataSource).
1375 if (p != 0) return INVALID_OPERATION;
1376
1377 if (NULL != endpoint) {
1378 mRetransmitEndpoint = *endpoint;
1379 mRetransmitEndpointValid = true;
1380 } else {
1381 mRetransmitEndpointValid = false;
1382 }
1383
1384 return NO_ERROR;
1385}
1386
John Grossman44a7e422012-06-21 17:29:24 -07001387status_t MediaPlayerService::Client::getRetransmitEndpoint(
1388 struct sockaddr_in* endpoint)
1389{
1390 if (NULL == endpoint)
1391 return BAD_VALUE;
1392
1393 sp<MediaPlayerBase> p = getPlayer();
1394
1395 if (p != NULL)
1396 return p->getRetransmitEndpoint(endpoint);
1397
1398 if (!mRetransmitEndpointValid)
1399 return NO_INIT;
1400
1401 *endpoint = mRetransmitEndpoint;
1402
1403 return NO_ERROR;
1404}
1405
Gloria Wangb483c472011-04-11 17:23:27 -07001406void MediaPlayerService::Client::notify(
1407 void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001408{
1409 Client* client = static_cast<Client*>(cookie);
James Dongb8a98252012-08-26 16:13:03 -07001410 if (client == NULL) {
1411 return;
1412 }
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001413
James Dongb8a98252012-08-26 16:13:03 -07001414 sp<IMediaPlayerClient> c;
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001415 sp<Client> nextClient;
1416 status_t errStartNext = NO_ERROR;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001417 {
1418 Mutex::Autolock l(client->mLock);
James Dongb8a98252012-08-26 16:13:03 -07001419 c = client->mClient;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001420 if (msg == MEDIA_PLAYBACK_COMPLETE && client->mNextClient != NULL) {
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001421 nextClient = client->mNextClient;
1422
John Grossmancb0b7552012-08-23 17:47:31 -07001423 if (client->mAudioOutput != NULL)
1424 client->mAudioOutput->switchToNextOutput();
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001425
1426 errStartNext = nextClient->start();
1427 }
1428 }
1429
1430 if (nextClient != NULL) {
1431 sp<IMediaPlayerClient> nc;
1432 {
1433 Mutex::Autolock l(nextClient->mLock);
1434 nc = nextClient->mClient;
1435 }
1436 if (nc != NULL) {
1437 if (errStartNext == NO_ERROR) {
1438 nc->notify(MEDIA_INFO, MEDIA_INFO_STARTED_AS_NEXT, 0, obj);
1439 } else {
1440 nc->notify(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN , 0, obj);
1441 ALOGE("gapless:start playback for next track failed, err(%d)", errStartNext);
Wei Jia2afac0c2016-01-07 12:13:07 -08001442 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001443 }
1444 }
1445
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001446 if (MEDIA_INFO == msg &&
Nicolas Catania48290382009-07-10 13:53:06 -07001447 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikoa64c8c72009-07-20 15:07:26 -07001448 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania48290382009-07-10 13:53:06 -07001449
1450 if(client->shouldDropMetadata(metadata_type)) {
1451 return;
1452 }
1453
1454 // Update the list of metadata that have changed. getMetadata
1455 // also access mMetadataUpdated and clears it.
1456 client->addNewMetadataUpdate(metadata_type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001457 }
James Dongb8a98252012-08-26 16:13:03 -07001458
1459 if (c != NULL) {
1460 ALOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
1461 c->notify(msg, ext1, ext2, obj);
1462 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001463}
1464
Nicolas Catania48290382009-07-10 13:53:06 -07001465
nikoa64c8c72009-07-20 15:07:26 -07001466bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001467{
Nicolas Catania48290382009-07-10 13:53:06 -07001468 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001469
Nicolas Catania48290382009-07-10 13:53:06 -07001470 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001471 return true;
1472 }
1473
Nicolas Catania48290382009-07-10 13:53:06 -07001474 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001475 return false;
Nicolas Catania48290382009-07-10 13:53:06 -07001476 } else {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001477 return true;
1478 }
1479}
1480
Nicolas Catania48290382009-07-10 13:53:06 -07001481
nikoa64c8c72009-07-20 15:07:26 -07001482void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania48290382009-07-10 13:53:06 -07001483 Mutex::Autolock lock(mLock);
1484 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1485 mMetadataUpdated.add(metadata_type);
1486 }
1487}
1488
Hassan Shojaniacefac142017-02-06 21:02:02 -08001489// Modular DRM
1490status_t MediaPlayerService::Client::prepareDrm(const uint8_t uuid[16],
1491 const Vector<uint8_t>& drmSessionId)
1492{
1493 ALOGV("[%d] prepareDrm", mConnId);
1494 sp<MediaPlayerBase> p = getPlayer();
1495 if (p == 0) return UNKNOWN_ERROR;
1496
1497 status_t ret = p->prepareDrm(uuid, drmSessionId);
1498 ALOGV("prepareDrm ret: %d", ret);
1499
1500 return ret;
1501}
1502
1503status_t MediaPlayerService::Client::releaseDrm()
1504{
1505 ALOGV("[%d] releaseDrm", mConnId);
1506 sp<MediaPlayerBase> p = getPlayer();
1507 if (p == 0) return UNKNOWN_ERROR;
1508
1509 status_t ret = p->releaseDrm();
1510 ALOGV("releaseDrm ret: %d", ret);
1511
1512 return ret;
1513}
1514
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001515#if CALLBACK_ANTAGONIZER
1516const int Antagonizer::interval = 10000; // 10 msecs
1517
1518Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1519 mExit(false), mActive(false), mClient(client), mCb(cb)
1520{
1521 createThread(callbackThread, this);
1522}
1523
1524void Antagonizer::kill()
1525{
1526 Mutex::Autolock _l(mLock);
1527 mActive = false;
1528 mExit = true;
1529 mCondition.wait(mLock);
1530}
1531
1532int Antagonizer::callbackThread(void* user)
1533{
Steve Blockb8a80522011-12-20 16:23:08 +00001534 ALOGD("Antagonizer started");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001535 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1536 while (!p->mExit) {
1537 if (p->mActive) {
Steve Block3856b092011-10-20 11:56:00 +01001538 ALOGV("send event");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001539 p->mCb(p->mClient, 0, 0, 0);
1540 }
1541 usleep(interval);
1542 }
1543 Mutex::Autolock _l(p->mLock);
1544 p->mCondition.signal();
Steve Blockb8a80522011-12-20 16:23:08 +00001545 ALOGD("Antagonizer stopped");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001546 return 0;
1547}
1548#endif
1549
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001550#undef LOG_TAG
1551#define LOG_TAG "AudioSink"
Andy Hung1afd0982016-11-08 16:13:44 -08001552MediaPlayerService::AudioOutput::AudioOutput(audio_session_t sessionId, uid_t uid, int pid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001553 const audio_attributes_t* attr)
Andreas Huber20111aa2009-07-14 16:56:47 -07001554 : mCallback(NULL),
Eric Laurenta514bdb2010-06-21 09:27:30 -07001555 mCallbackCookie(NULL),
Marco Nelissen6b74d672012-02-28 16:07:44 -08001556 mCallbackData(NULL),
Andy Hungd1c74342015-07-07 16:54:23 -07001557 mStreamType(AUDIO_STREAM_MUSIC),
Andy Hungd1c74342015-07-07 16:54:23 -07001558 mLeftVolume(1.0),
1559 mRightVolume(1.0),
1560 mPlaybackRate(AUDIO_PLAYBACK_RATE_DEFAULT),
1561 mSampleRateHz(0),
1562 mMsecsPerFrame(0),
1563 mFrameSize(0),
Eric Laurent1948eb32012-04-13 16:50:19 -07001564 mSessionId(sessionId),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001565 mUid(uid),
Marco Nelissend457c972014-02-11 08:47:07 -08001566 mPid(pid),
Andy Hungd1c74342015-07-07 16:54:23 -07001567 mSendLevel(0.0),
1568 mAuxEffectId(0),
Andy Hung4ef88d72017-02-21 19:47:53 -08001569 mFlags(AUDIO_OUTPUT_FLAG_NONE),
1570 mVolumeHandler(new VolumeHandler())
Andy Hungd1c74342015-07-07 16:54:23 -07001571{
Steve Block3856b092011-10-20 11:56:00 +01001572 ALOGV("AudioOutput(%d)", sessionId);
Eric Laurent43562692015-07-15 16:49:07 -07001573 if (attr != NULL) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001574 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1575 if (mAttributes != NULL) {
1576 memcpy(mAttributes, attr, sizeof(audio_attributes_t));
1577 mStreamType = audio_attributes_to_stream_type(attr);
1578 }
1579 } else {
1580 mAttributes = NULL;
Eric Laurent43562692015-07-15 16:49:07 -07001581 }
1582
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001583 setMinBufferCount();
1584}
1585
1586MediaPlayerService::AudioOutput::~AudioOutput()
1587{
1588 close();
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001589 free(mAttributes);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001590 delete mCallbackData;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001591}
1592
Andy Hungd1c74342015-07-07 16:54:23 -07001593//static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001594void MediaPlayerService::AudioOutput::setMinBufferCount()
1595{
1596 char value[PROPERTY_VALUE_MAX];
1597 if (property_get("ro.kernel.qemu", value, 0)) {
1598 mIsOnEmulator = true;
1599 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1600 }
1601}
1602
Andy Hungd1c74342015-07-07 16:54:23 -07001603// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001604bool MediaPlayerService::AudioOutput::isOnEmulator()
1605{
Andy Hungd1c74342015-07-07 16:54:23 -07001606 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001607 return mIsOnEmulator;
1608}
1609
Andy Hungd1c74342015-07-07 16:54:23 -07001610// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001611int MediaPlayerService::AudioOutput::getMinBufferCount()
1612{
Andy Hungd1c74342015-07-07 16:54:23 -07001613 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001614 return mMinBufferCount;
1615}
1616
1617ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1618{
Andy Hungd1c74342015-07-07 16:54:23 -07001619 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001620 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001621 return mTrack->frameCount() * mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001622}
1623
1624ssize_t MediaPlayerService::AudioOutput::frameCount() const
1625{
Andy Hungd1c74342015-07-07 16:54:23 -07001626 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001627 if (mTrack == 0) return NO_INIT;
1628 return mTrack->frameCount();
1629}
1630
1631ssize_t MediaPlayerService::AudioOutput::channelCount() const
1632{
Andy Hungd1c74342015-07-07 16:54:23 -07001633 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001634 if (mTrack == 0) return NO_INIT;
1635 return mTrack->channelCount();
1636}
1637
1638ssize_t MediaPlayerService::AudioOutput::frameSize() const
1639{
Andy Hungd1c74342015-07-07 16:54:23 -07001640 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001641 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001642 return mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001643}
1644
1645uint32_t MediaPlayerService::AudioOutput::latency () const
1646{
Andy Hungd1c74342015-07-07 16:54:23 -07001647 Mutex::Autolock lock(mLock);
Eric Laurentdb354e52012-03-05 17:27:11 -08001648 if (mTrack == 0) return 0;
1649 return mTrack->latency();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001650}
1651
1652float MediaPlayerService::AudioOutput::msecsPerFrame() const
1653{
Andy Hungd1c74342015-07-07 16:54:23 -07001654 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001655 return mMsecsPerFrame;
1656}
1657
Marco Nelissen4110c102012-03-29 09:31:28 -07001658status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position) const
Eric Laurent342e9cf2010-01-19 17:37:09 -08001659{
Andy Hungd1c74342015-07-07 16:54:23 -07001660 Mutex::Autolock lock(mLock);
Eric Laurent342e9cf2010-01-19 17:37:09 -08001661 if (mTrack == 0) return NO_INIT;
1662 return mTrack->getPosition(position);
1663}
1664
Lajos Molnar06ad1522014-08-28 07:27:44 -07001665status_t MediaPlayerService::AudioOutput::getTimestamp(AudioTimestamp &ts) const
1666{
Andy Hungd1c74342015-07-07 16:54:23 -07001667 Mutex::Autolock lock(mLock);
Lajos Molnar06ad1522014-08-28 07:27:44 -07001668 if (mTrack == 0) return NO_INIT;
1669 return mTrack->getTimestamp(ts);
1670}
1671
Wei Jiac4ac8172015-10-21 10:35:48 -07001672// TODO: Remove unnecessary calls to getPlayedOutDurationUs()
1673// as it acquires locks and may query the audio driver.
1674//
1675// Some calls could conceivably retrieve extrapolated data instead of
1676// accessing getTimestamp() or getPosition() every time a data buffer with
1677// a media time is received.
1678//
1679// Calculate duration of played samples if played at normal rate (i.e., 1.0).
1680int64_t MediaPlayerService::AudioOutput::getPlayedOutDurationUs(int64_t nowUs) const
1681{
1682 Mutex::Autolock lock(mLock);
1683 if (mTrack == 0 || mSampleRateHz == 0) {
Wei Jia213f4902015-10-22 08:55:25 -07001684 return 0;
Wei Jiac4ac8172015-10-21 10:35:48 -07001685 }
1686
1687 uint32_t numFramesPlayed;
Andy Hung5d313802016-10-10 15:09:39 -07001688 int64_t numFramesPlayedAtUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001689 AudioTimestamp ts;
Wei Jiac4ac8172015-10-21 10:35:48 -07001690
1691 status_t res = mTrack->getTimestamp(ts);
1692 if (res == OK) { // case 1: mixing audio tracks and offloaded tracks.
1693 numFramesPlayed = ts.mPosition;
Andy Hung5d313802016-10-10 15:09:39 -07001694 numFramesPlayedAtUs = ts.mTime.tv_sec * 1000000LL + ts.mTime.tv_nsec / 1000;
1695 //ALOGD("getTimestamp: OK %d %lld", numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001696 } else if (res == WOULD_BLOCK) { // case 2: transitory state on start of a new track
1697 numFramesPlayed = 0;
Andy Hung5d313802016-10-10 15:09:39 -07001698 numFramesPlayedAtUs = nowUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001699 //ALOGD("getTimestamp: WOULD_BLOCK %d %lld",
Andy Hung5d313802016-10-10 15:09:39 -07001700 // numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001701 } else { // case 3: transitory at new track or audio fast tracks.
1702 res = mTrack->getPosition(&numFramesPlayed);
1703 CHECK_EQ(res, (status_t)OK);
Andy Hung5d313802016-10-10 15:09:39 -07001704 numFramesPlayedAtUs = nowUs;
1705 numFramesPlayedAtUs += 1000LL * mTrack->latency() / 2; /* XXX */
1706 //ALOGD("getPosition: %u %lld", numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001707 }
1708
1709 // CHECK_EQ(numFramesPlayed & (1 << 31), 0); // can't be negative until 12.4 hrs, test
1710 // TODO: remove the (int32_t) casting below as it may overflow at 12.4 hours.
1711 int64_t durationUs = (int64_t)((int32_t)numFramesPlayed * 1000000LL / mSampleRateHz)
Andy Hung5d313802016-10-10 15:09:39 -07001712 + nowUs - numFramesPlayedAtUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001713 if (durationUs < 0) {
1714 // Occurs when numFramesPlayed position is very small and the following:
1715 // (1) In case 1, the time nowUs is computed before getTimestamp() is called and
Andy Hung5d313802016-10-10 15:09:39 -07001716 // numFramesPlayedAtUs is greater than nowUs by time more than numFramesPlayed.
Wei Jiac4ac8172015-10-21 10:35:48 -07001717 // (2) In case 3, using getPosition and adding mAudioSink->latency() to
Andy Hung5d313802016-10-10 15:09:39 -07001718 // numFramesPlayedAtUs, by a time amount greater than numFramesPlayed.
Wei Jiac4ac8172015-10-21 10:35:48 -07001719 //
1720 // Both of these are transitory conditions.
1721 ALOGV("getPlayedOutDurationUs: negative duration %lld set to zero", (long long)durationUs);
1722 durationUs = 0;
1723 }
1724 ALOGV("getPlayedOutDurationUs(%lld) nowUs(%lld) frames(%u) framesAt(%lld)",
Andy Hung5d313802016-10-10 15:09:39 -07001725 (long long)durationUs, (long long)nowUs,
1726 numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001727 return durationUs;
1728}
1729
Marco Nelissen4110c102012-03-29 09:31:28 -07001730status_t MediaPlayerService::AudioOutput::getFramesWritten(uint32_t *frameswritten) const
1731{
Andy Hungd1c74342015-07-07 16:54:23 -07001732 Mutex::Autolock lock(mLock);
Marco Nelissen4110c102012-03-29 09:31:28 -07001733 if (mTrack == 0) return NO_INIT;
Andy Hung2f6e73d2016-04-08 12:12:58 -07001734 ExtendedTimestamp ets;
1735 status_t status = mTrack->getTimestamp(&ets);
1736 if (status == OK || status == WOULD_BLOCK) {
1737 *frameswritten = (uint32_t)ets.mPosition[ExtendedTimestamp::LOCATION_CLIENT];
1738 }
1739 return status;
Marco Nelissen4110c102012-03-29 09:31:28 -07001740}
1741
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001742status_t MediaPlayerService::AudioOutput::setParameters(const String8& keyValuePairs)
1743{
Andy Hungd1c74342015-07-07 16:54:23 -07001744 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001745 if (mTrack == 0) return NO_INIT;
1746 return mTrack->setParameters(keyValuePairs);
1747}
1748
1749String8 MediaPlayerService::AudioOutput::getParameters(const String8& keys)
1750{
Andy Hungd1c74342015-07-07 16:54:23 -07001751 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001752 if (mTrack == 0) return String8::empty();
1753 return mTrack->getParameters(keys);
1754}
1755
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001756void MediaPlayerService::AudioOutput::setAudioAttributes(const audio_attributes_t * attributes) {
Andy Hungd1c74342015-07-07 16:54:23 -07001757 Mutex::Autolock lock(mLock);
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001758 if (attributes == NULL) {
1759 free(mAttributes);
1760 mAttributes = NULL;
1761 } else {
1762 if (mAttributes == NULL) {
1763 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1764 }
1765 memcpy(mAttributes, attributes, sizeof(audio_attributes_t));
Eric Laurent43562692015-07-15 16:49:07 -07001766 mStreamType = audio_attributes_to_stream_type(attributes);
1767 }
1768}
1769
1770void MediaPlayerService::AudioOutput::setAudioStreamType(audio_stream_type_t streamType)
1771{
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001772 Mutex::Autolock lock(mLock);
Eric Laurent43562692015-07-15 16:49:07 -07001773 // do not allow direct stream type modification if attributes have been set
1774 if (mAttributes == NULL) {
1775 mStreamType = streamType;
1776 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001777}
1778
Andy Hungd1c74342015-07-07 16:54:23 -07001779void MediaPlayerService::AudioOutput::deleteRecycledTrack_l()
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001780{
Andy Hungd1c74342015-07-07 16:54:23 -07001781 ALOGV("deleteRecycledTrack_l");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001782 if (mRecycledTrack != 0) {
1783
1784 if (mCallbackData != NULL) {
1785 mCallbackData->setOutput(NULL);
1786 mCallbackData->endTrackSwitch();
1787 }
1788
1789 if ((mRecycledTrack->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) {
Andy Hunge13f8a62016-03-30 14:20:42 -07001790 int32_t msec = 0;
1791 if (!mRecycledTrack->stopped()) { // check if active
1792 (void)mRecycledTrack->pendingDuration(&msec);
1793 }
1794 mRecycledTrack->stop(); // ensure full data drain
1795 ALOGD("deleting recycled track, waiting for data drain (%d msec)", msec);
1796 if (msec > 0) {
1797 static const int32_t WAIT_LIMIT_MS = 3000;
1798 if (msec > WAIT_LIMIT_MS) {
1799 msec = WAIT_LIMIT_MS;
1800 }
1801 usleep(msec * 1000LL);
1802 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001803 }
1804 // An offloaded track isn't flushed because the STREAM_END is reported
1805 // slightly prematurely to allow time for the gapless track switch
1806 // but this means that if we decide not to recycle the track there
1807 // could be a small amount of residual data still playing. We leave
1808 // AudioFlinger to drain the track.
1809
1810 mRecycledTrack.clear();
Andy Hungd1c74342015-07-07 16:54:23 -07001811 close_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001812 delete mCallbackData;
1813 mCallbackData = NULL;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001814 }
1815}
1816
Andy Hungd1c74342015-07-07 16:54:23 -07001817void MediaPlayerService::AudioOutput::close_l()
1818{
1819 mTrack.clear();
1820}
1821
Andreas Huber20111aa2009-07-14 16:56:47 -07001822status_t MediaPlayerService::AudioOutput::open(
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001823 uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
1824 audio_format_t format, int bufferCount,
Eric Laurent1948eb32012-04-13 16:50:19 -07001825 AudioCallback cb, void *cookie,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001826 audio_output_flags_t flags,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001827 const audio_offload_info_t *offloadInfo,
Andy Hung179652e2015-05-31 22:49:46 -07001828 bool doNotReconnect,
1829 uint32_t suggestedFrameCount)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001830{
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001831 ALOGV("open(%u, %d, 0x%x, 0x%x, %d, %d 0x%x)", sampleRate, channelCount, channelMask,
1832 format, bufferCount, mSessionId, flags);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001833
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001834 // offloading is only supported in callback mode for now.
1835 // offloadInfo must be present if offload flag is set
1836 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) &&
1837 ((cb == NULL) || (offloadInfo == NULL))) {
1838 return BAD_VALUE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001839 }
1840
Andy Hung179652e2015-05-31 22:49:46 -07001841 // compute frame count for the AudioTrack internal buffer
1842 size_t frameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001843 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1844 frameCount = 0; // AudioTrack will get frame count from AudioFlinger
1845 } else {
Andy Hung179652e2015-05-31 22:49:46 -07001846 // try to estimate the buffer processing fetch size from AudioFlinger.
1847 // framesPerBuffer is approximate and generally correct, except when it's not :-).
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001848 uint32_t afSampleRate;
1849 size_t afFrameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001850 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1851 return NO_INIT;
1852 }
1853 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1854 return NO_INIT;
1855 }
Andy Hung179652e2015-05-31 22:49:46 -07001856 const size_t framesPerBuffer =
1857 (unsigned long long)sampleRate * afFrameCount / afSampleRate;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001858
Andy Hung179652e2015-05-31 22:49:46 -07001859 if (bufferCount == 0) {
1860 // use suggestedFrameCount
1861 bufferCount = (suggestedFrameCount + framesPerBuffer - 1) / framesPerBuffer;
1862 }
1863 // Check argument bufferCount against the mininum buffer count
1864 if (bufferCount != 0 && bufferCount < mMinBufferCount) {
1865 ALOGV("bufferCount (%d) increased to %d", bufferCount, mMinBufferCount);
1866 bufferCount = mMinBufferCount;
1867 }
1868 // if frameCount is 0, then AudioTrack will get frame count from AudioFlinger
1869 // which will be the minimum size permitted.
1870 frameCount = bufferCount * framesPerBuffer;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001871 }
Andreas Huber20111aa2009-07-14 16:56:47 -07001872
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001873 if (channelMask == CHANNEL_MASK_USE_CHANNEL_ORDER) {
Glenn Kastenab334fd2012-03-14 12:56:06 -07001874 channelMask = audio_channel_out_mask_from_count(channelCount);
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001875 if (0 == channelMask) {
1876 ALOGE("open() error, can\'t derive mask for %d audio channels", channelCount);
1877 return NO_INIT;
1878 }
1879 }
Eric Laurent1948eb32012-04-13 16:50:19 -07001880
Andy Hungd1c74342015-07-07 16:54:23 -07001881 Mutex::Autolock lock(mLock);
Andy Hung179652e2015-05-31 22:49:46 -07001882 mCallback = cb;
1883 mCallbackCookie = cookie;
1884
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001885 // Check whether we can recycle the track
1886 bool reuse = false;
1887 bool bothOffloaded = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001888
Glenn Kasten2799d742013-05-30 14:33:29 -07001889 if (mRecycledTrack != 0) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001890 // check whether we are switching between two offloaded tracks
1891 bothOffloaded = (flags & mRecycledTrack->getFlags()
1892 & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0;
Marco Nelissen67295b52012-06-11 14:52:53 -07001893
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001894 // check if the existing track can be reused as-is, or if a new track needs to be created.
1895 reuse = true;
1896
Marco Nelissen67295b52012-06-11 14:52:53 -07001897 if ((mCallbackData == NULL && mCallback != NULL) ||
1898 (mCallbackData != NULL && mCallback == NULL)) {
1899 // recycled track uses callbacks but the caller wants to use writes, or vice versa
1900 ALOGV("can't chain callback and write");
1901 reuse = false;
1902 } else if ((mRecycledTrack->getSampleRate() != sampleRate) ||
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001903 (mRecycledTrack->channelCount() != (uint32_t)channelCount) ) {
1904 ALOGV("samplerate, channelcount differ: %u/%u Hz, %u/%d ch",
Marco Nelissen67295b52012-06-11 14:52:53 -07001905 mRecycledTrack->getSampleRate(), sampleRate,
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001906 mRecycledTrack->channelCount(), channelCount);
Marco Nelissen67295b52012-06-11 14:52:53 -07001907 reuse = false;
1908 } else if (flags != mFlags) {
1909 ALOGV("output flags differ %08x/%08x", flags, mFlags);
1910 reuse = false;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001911 } else if (mRecycledTrack->format() != format) {
1912 reuse = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001913 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001914 } else {
1915 ALOGV("no track available to recycle");
1916 }
1917
1918 ALOGV_IF(bothOffloaded, "both tracks offloaded");
1919
1920 // If we can't recycle and both tracks are offloaded
1921 // we must close the previous output before opening a new one
1922 if (bothOffloaded && !reuse) {
1923 ALOGV("both offloaded and not recycling");
Andy Hungd1c74342015-07-07 16:54:23 -07001924 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001925 }
1926
1927 sp<AudioTrack> t;
1928 CallbackData *newcbd = NULL;
1929
1930 // We don't attempt to create a new track if we are recycling an
1931 // offloaded track. But, if we are recycling a non-offloaded or we
1932 // are switching where one is offloaded and one isn't then we create
1933 // the new track in advance so that we can read additional stream info
1934
1935 if (!(reuse && bothOffloaded)) {
1936 ALOGV("creating new AudioTrack");
1937
1938 if (mCallback != NULL) {
1939 newcbd = new CallbackData(this);
1940 t = new AudioTrack(
1941 mStreamType,
1942 sampleRate,
1943 format,
1944 channelMask,
1945 frameCount,
1946 flags,
1947 CallbackWrapper,
1948 newcbd,
1949 0, // notification frames
1950 mSessionId,
1951 AudioTrack::TRANSFER_CALLBACK,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001952 offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -08001953 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001954 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001955 mAttributes,
1956 doNotReconnect);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001957 } else {
Andy Hungff874dc2016-04-11 16:49:09 -07001958 // TODO: Due to buffer memory concerns, we use a max target playback speed
1959 // based on mPlaybackRate at the time of open (instead of kMaxRequiredSpeed),
1960 // also clamping the target speed to 1.0 <= targetSpeed <= kMaxRequiredSpeed.
1961 const float targetSpeed =
1962 std::min(std::max(mPlaybackRate.mSpeed, 1.0f), kMaxRequiredSpeed);
1963 ALOGW_IF(targetSpeed != mPlaybackRate.mSpeed,
1964 "track target speed:%f clamped from playback speed:%f",
1965 targetSpeed, mPlaybackRate.mSpeed);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001966 t = new AudioTrack(
1967 mStreamType,
1968 sampleRate,
1969 format,
1970 channelMask,
1971 frameCount,
1972 flags,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001973 NULL, // callback
1974 NULL, // user data
1975 0, // notification frames
1976 mSessionId,
1977 AudioTrack::TRANSFER_DEFAULT,
1978 NULL, // offload info
Marco Nelissend457c972014-02-11 08:47:07 -08001979 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001980 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001981 mAttributes,
Andy Hungff874dc2016-04-11 16:49:09 -07001982 doNotReconnect,
1983 targetSpeed);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001984 }
1985
1986 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1987 ALOGE("Unable to create audio track");
1988 delete newcbd;
Glenn Kasten3e98ecd2015-05-18 13:13:24 -07001989 // t goes out of scope, so reference count drops to zero
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001990 return NO_INIT;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001991 } else {
1992 // successful AudioTrack initialization implies a legacy stream type was generated
1993 // from the audio attributes
1994 mStreamType = t->streamType();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001995 }
1996 }
1997
1998 if (reuse) {
1999 CHECK(mRecycledTrack != NULL);
2000
2001 if (!bothOffloaded) {
2002 if (mRecycledTrack->frameCount() != t->frameCount()) {
Andy Hung833b4752016-04-04 17:15:48 -07002003 ALOGV("framecount differs: %zu/%zu frames",
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002004 mRecycledTrack->frameCount(), t->frameCount());
2005 reuse = false;
2006 }
2007 }
2008
Marco Nelissen67295b52012-06-11 14:52:53 -07002009 if (reuse) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002010 ALOGV("chaining to next output and recycling track");
Andy Hungd1c74342015-07-07 16:54:23 -07002011 close_l();
Marco Nelissen67295b52012-06-11 14:52:53 -07002012 mTrack = mRecycledTrack;
Glenn Kasten2799d742013-05-30 14:33:29 -07002013 mRecycledTrack.clear();
Marco Nelissen67295b52012-06-11 14:52:53 -07002014 if (mCallbackData != NULL) {
2015 mCallbackData->setOutput(this);
2016 }
Marco Nelissen67295b52012-06-11 14:52:53 -07002017 delete newcbd;
Wei Jiae0bbac92016-07-18 16:04:53 -07002018 return updateTrack();
Marco Nelissen67295b52012-06-11 14:52:53 -07002019 }
Marco Nelissen67295b52012-06-11 14:52:53 -07002020 }
2021
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002022 // we're not going to reuse the track, unblock and flush it
2023 // this was done earlier if both tracks are offloaded
2024 if (!bothOffloaded) {
Andy Hungd1c74342015-07-07 16:54:23 -07002025 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002026 }
2027
2028 CHECK((t != NULL) && ((mCallback == NULL) || (newcbd != NULL)));
2029
Marco Nelissen67295b52012-06-11 14:52:53 -07002030 mCallbackData = newcbd;
Steve Block3856b092011-10-20 11:56:00 +01002031 ALOGV("setVolume");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002032 t->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07002033
Andy Hung4ef88d72017-02-21 19:47:53 -08002034 // Dispatch any queued VolumeShapers when the track was not open.
2035 mVolumeHandler->forall([&t](const sp<VolumeShaper::Configuration> &configuration,
2036 const sp<VolumeShaper::Operation> &operation) -> VolumeShaper::Status {
2037 return t->applyVolumeShaper(configuration, operation);
2038 });
2039 mVolumeHandler->reset(); // After dispatching, clear VolumeShaper queue.
2040
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002041 mSampleRateHz = sampleRate;
Preetam Singh Ranawat2e17eef2015-08-12 12:11:46 -07002042 mFlags = flags;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002043 mMsecsPerFrame = 1E3f / (mPlaybackRate.mSpeed * sampleRate);
Andy Hungd1c74342015-07-07 16:54:23 -07002044 mFrameSize = t->frameSize();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002045 mTrack = t;
Eric Laurent2beeb502010-07-16 07:43:46 -07002046
Wei Jiae0bbac92016-07-18 16:04:53 -07002047 return updateTrack();
2048}
2049
2050status_t MediaPlayerService::AudioOutput::updateTrack() {
2051 if (mTrack == NULL) {
2052 return NO_ERROR;
2053 }
2054
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002055 status_t res = NO_ERROR;
Wei Jia0162d002015-06-09 11:59:33 -07002056 // Note some output devices may give us a direct track even though we don't specify it.
2057 // Example: Line application b/17459982.
Wei Jiae0bbac92016-07-18 16:04:53 -07002058 if ((mTrack->getFlags()
2059 & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) {
2060 res = mTrack->setPlaybackRate(mPlaybackRate);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002061 if (res == NO_ERROR) {
Wei Jiae0bbac92016-07-18 16:04:53 -07002062 mTrack->setAuxEffectSendLevel(mSendLevel);
2063 res = mTrack->attachAuxEffect(mAuxEffectId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002064 }
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002065 }
Wei Jiae0bbac92016-07-18 16:04:53 -07002066 ALOGV("updateTrack() DONE status %d", res);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002067 return res;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002068}
2069
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002070status_t MediaPlayerService::AudioOutput::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002071{
Steve Block3856b092011-10-20 11:56:00 +01002072 ALOGV("start");
Andy Hungd1c74342015-07-07 16:54:23 -07002073 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08002074 if (mCallbackData != NULL) {
2075 mCallbackData->endTrackSwitch();
2076 }
Glenn Kasten2799d742013-05-30 14:33:29 -07002077 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002078 mTrack->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07002079 mTrack->setAuxEffectSendLevel(mSendLevel);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002080 return mTrack->start();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002081 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002082 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002083}
2084
Marco Nelissen6b74d672012-02-28 16:07:44 -08002085void MediaPlayerService::AudioOutput::setNextOutput(const sp<AudioOutput>& nextOutput) {
Andy Hungd1c74342015-07-07 16:54:23 -07002086 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08002087 mNextOutput = nextOutput;
2088}
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08002089
Marco Nelissen6b74d672012-02-28 16:07:44 -08002090void MediaPlayerService::AudioOutput::switchToNextOutput() {
2091 ALOGV("switchToNextOutput");
Andy Hungd1c74342015-07-07 16:54:23 -07002092
2093 // Try to acquire the callback lock before moving track (without incurring deadlock).
2094 const unsigned kMaxSwitchTries = 100;
2095 Mutex::Autolock lock(mLock);
2096 for (unsigned tries = 0;;) {
2097 if (mTrack == 0) {
2098 return;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002099 }
Andy Hungd1c74342015-07-07 16:54:23 -07002100 if (mNextOutput != NULL && mNextOutput != this) {
2101 if (mCallbackData != NULL) {
2102 // two alternative approaches
2103#if 1
2104 CallbackData *callbackData = mCallbackData;
2105 mLock.unlock();
2106 // proper acquisition sequence
2107 callbackData->lock();
2108 mLock.lock();
2109 // Caution: it is unlikely that someone deleted our callback or changed our target
2110 if (callbackData != mCallbackData || mNextOutput == NULL || mNextOutput == this) {
2111 // fatal if we are starved out.
2112 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
2113 "switchToNextOutput() cannot obtain correct lock sequence");
2114 callbackData->unlock();
2115 continue;
2116 }
2117 callbackData->mSwitching = true; // begin track switch
Wei Jiaadee56a2016-08-05 15:40:34 -07002118 callbackData->setOutput(NULL);
Andy Hungd1c74342015-07-07 16:54:23 -07002119#else
2120 // tryBeginTrackSwitch() returns false if the callback has the lock.
2121 if (!mCallbackData->tryBeginTrackSwitch()) {
2122 // fatal if we are starved out.
2123 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
2124 "switchToNextOutput() cannot obtain callback lock");
2125 mLock.unlock();
2126 usleep(5 * 1000 /* usec */); // allow callback to use AudioOutput
2127 mLock.lock();
2128 continue;
2129 }
2130#endif
2131 }
2132
2133 Mutex::Autolock nextLock(mNextOutput->mLock);
2134
2135 // If the next output track is not NULL, then it has been
2136 // opened already for playback.
2137 // This is possible even without the next player being started,
2138 // for example, the next player could be prepared and seeked.
2139 //
2140 // Presuming it isn't advisable to force the track over.
2141 if (mNextOutput->mTrack == NULL) {
2142 ALOGD("Recycling track for gapless playback");
2143 delete mNextOutput->mCallbackData;
2144 mNextOutput->mCallbackData = mCallbackData;
2145 mNextOutput->mRecycledTrack = mTrack;
2146 mNextOutput->mSampleRateHz = mSampleRateHz;
2147 mNextOutput->mMsecsPerFrame = mMsecsPerFrame;
Andy Hungd1c74342015-07-07 16:54:23 -07002148 mNextOutput->mFlags = mFlags;
2149 mNextOutput->mFrameSize = mFrameSize;
2150 close_l();
2151 mCallbackData = NULL; // destruction handled by mNextOutput
2152 } else {
2153 ALOGW("Ignoring gapless playback because next player has already started");
2154 // remove track in case resource needed for future players.
2155 if (mCallbackData != NULL) {
2156 mCallbackData->endTrackSwitch(); // release lock for callbacks before close.
2157 }
2158 close_l();
2159 }
2160 }
2161 break;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002162 }
2163}
2164
Wei Jia7d3f4df2015-03-03 15:28:00 -08002165ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002166{
Andy Hungd1c74342015-07-07 16:54:23 -07002167 Mutex::Autolock lock(mLock);
Glenn Kastenadad3d72014-02-21 14:51:43 -08002168 LOG_ALWAYS_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
Andreas Huber20111aa2009-07-14 16:56:47 -07002169
Steve Block3856b092011-10-20 11:56:00 +01002170 //ALOGV("write(%p, %u)", buffer, size);
Glenn Kasten2799d742013-05-30 14:33:29 -07002171 if (mTrack != 0) {
Andy Hung2f6e73d2016-04-08 12:12:58 -07002172 return mTrack->write(buffer, size, blocking);
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07002173 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002174 return NO_INIT;
2175}
2176
2177void MediaPlayerService::AudioOutput::stop()
2178{
Steve Block3856b092011-10-20 11:56:00 +01002179 ALOGV("stop");
Andy Hungd1c74342015-07-07 16:54:23 -07002180 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002181 if (mTrack != 0) mTrack->stop();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002182}
2183
2184void MediaPlayerService::AudioOutput::flush()
2185{
Steve Block3856b092011-10-20 11:56:00 +01002186 ALOGV("flush");
Andy Hungd1c74342015-07-07 16:54:23 -07002187 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002188 if (mTrack != 0) mTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002189}
2190
2191void MediaPlayerService::AudioOutput::pause()
2192{
Steve Block3856b092011-10-20 11:56:00 +01002193 ALOGV("pause");
Andy Hungd1c74342015-07-07 16:54:23 -07002194 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002195 if (mTrack != 0) mTrack->pause();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002196}
2197
2198void MediaPlayerService::AudioOutput::close()
2199{
Steve Block3856b092011-10-20 11:56:00 +01002200 ALOGV("close");
Erik Wolsheimer7845a1f2015-10-30 12:07:52 -07002201 sp<AudioTrack> track;
2202 {
2203 Mutex::Autolock lock(mLock);
2204 track = mTrack;
2205 close_l(); // clears mTrack
2206 }
2207 // destruction of the track occurs outside of mutex.
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002208}
2209
2210void MediaPlayerService::AudioOutput::setVolume(float left, float right)
2211{
Steve Block3856b092011-10-20 11:56:00 +01002212 ALOGV("setVolume(%f, %f)", left, right);
Andy Hungd1c74342015-07-07 16:54:23 -07002213 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002214 mLeftVolume = left;
2215 mRightVolume = right;
Glenn Kasten2799d742013-05-30 14:33:29 -07002216 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002217 mTrack->setVolume(left, right);
2218 }
2219}
2220
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002221status_t MediaPlayerService::AudioOutput::setPlaybackRate(const AudioPlaybackRate &rate)
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002222{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002223 ALOGV("setPlaybackRate(%f %f %d %d)",
2224 rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Andy Hungd1c74342015-07-07 16:54:23 -07002225 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002226 if (mTrack == 0) {
2227 // remember rate so that we can set it when the track is opened
2228 mPlaybackRate = rate;
2229 return OK;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002230 }
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002231 status_t res = mTrack->setPlaybackRate(rate);
2232 if (res != NO_ERROR) {
2233 return res;
2234 }
2235 // rate.mSpeed is always greater than 0 if setPlaybackRate succeeded
2236 CHECK_GT(rate.mSpeed, 0.f);
2237 mPlaybackRate = rate;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002238 if (mSampleRateHz != 0) {
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002239 mMsecsPerFrame = 1E3f / (rate.mSpeed * mSampleRateHz);
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002240 }
2241 return res;
2242}
2243
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002244status_t MediaPlayerService::AudioOutput::getPlaybackRate(AudioPlaybackRate *rate)
2245{
2246 ALOGV("setPlaybackRate");
Andy Hungd1c74342015-07-07 16:54:23 -07002247 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002248 if (mTrack == 0) {
2249 return NO_INIT;
2250 }
2251 *rate = mTrack->getPlaybackRate();
2252 return NO_ERROR;
2253}
2254
Eric Laurent2beeb502010-07-16 07:43:46 -07002255status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
2256{
Steve Block3856b092011-10-20 11:56:00 +01002257 ALOGV("setAuxEffectSendLevel(%f)", level);
Andy Hungd1c74342015-07-07 16:54:23 -07002258 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002259 mSendLevel = level;
Glenn Kasten2799d742013-05-30 14:33:29 -07002260 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002261 return mTrack->setAuxEffectSendLevel(level);
2262 }
2263 return NO_ERROR;
2264}
2265
2266status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
2267{
Steve Block3856b092011-10-20 11:56:00 +01002268 ALOGV("attachAuxEffect(%d)", effectId);
Andy Hungd1c74342015-07-07 16:54:23 -07002269 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002270 mAuxEffectId = effectId;
Glenn Kasten2799d742013-05-30 14:33:29 -07002271 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002272 return mTrack->attachAuxEffect(effectId);
2273 }
2274 return NO_ERROR;
2275}
2276
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002277VolumeShaper::Status MediaPlayerService::AudioOutput::applyVolumeShaper(
2278 const sp<VolumeShaper::Configuration>& configuration,
2279 const sp<VolumeShaper::Operation>& operation)
2280{
2281 Mutex::Autolock lock(mLock);
2282 ALOGV("AudioOutput::applyVolumeShaper");
Andy Hung4ef88d72017-02-21 19:47:53 -08002283
2284 // We take ownership of the VolumeShaper if set before the track is created.
2285 mVolumeHandler->setIdIfNecessary(configuration);
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002286 if (mTrack != 0) {
2287 return mTrack->applyVolumeShaper(configuration, operation);
Andy Hung4ef88d72017-02-21 19:47:53 -08002288 } else {
2289 return mVolumeHandler->applyVolumeShaper(configuration, operation);
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002290 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002291}
2292
2293sp<VolumeShaper::State> MediaPlayerService::AudioOutput::getVolumeShaperState(int id)
2294{
2295 Mutex::Autolock lock(mLock);
2296 if (mTrack != 0) {
2297 return mTrack->getVolumeShaperState(id);
Andy Hung4ef88d72017-02-21 19:47:53 -08002298 } else {
2299 return mVolumeHandler->getVolumeShaperState(id);
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002300 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002301}
2302
Andreas Huber20111aa2009-07-14 16:56:47 -07002303// static
2304void MediaPlayerService::AudioOutput::CallbackWrapper(
Glenn Kastend217a8c2011-06-01 15:20:35 -07002305 int event, void *cookie, void *info) {
Steve Block3856b092011-10-20 11:56:00 +01002306 //ALOGV("callbackwrapper");
Marco Nelissen6b74d672012-02-28 16:07:44 -08002307 CallbackData *data = (CallbackData*)cookie;
Andy Hungd1c74342015-07-07 16:54:23 -07002308 // lock to ensure we aren't caught in the middle of a track switch.
Marco Nelissen6b74d672012-02-28 16:07:44 -08002309 data->lock();
2310 AudioOutput *me = data->getOutput();
Andreas Huber20111aa2009-07-14 16:56:47 -07002311 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002312 if (me == NULL) {
2313 // no output set, likely because the track was scheduled to be reused
2314 // by another player, but the format turned out to be incompatible.
2315 data->unlock();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002316 if (buffer != NULL) {
2317 buffer->size = 0;
2318 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08002319 return;
2320 }
Andreas Huber20111aa2009-07-14 16:56:47 -07002321
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002322 switch(event) {
2323 case AudioTrack::EVENT_MORE_DATA: {
2324 size_t actualSize = (*me->mCallback)(
2325 me, buffer->raw, buffer->size, me->mCallbackCookie,
2326 CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002327
Andy Hung719b46b2015-05-31 22:18:25 -07002328 // Log when no data is returned from the callback.
2329 // (1) We may have no data (especially with network streaming sources).
2330 // (2) We may have reached the EOS and the audio track is not stopped yet.
2331 // Note that AwesomePlayer/AudioPlayer will only return zero size when it reaches the EOS.
2332 // NuPlayerRenderer will return zero when it doesn't have data (it doesn't block to fill).
2333 //
2334 // This is a benign busy-wait, with the next data request generated 10 ms or more later;
2335 // nevertheless for power reasons, we don't want to see too many of these.
Andreas Huber2e8ffaf2010-02-18 16:45:13 -08002336
Andy Hung719b46b2015-05-31 22:18:25 -07002337 ALOGV_IF(actualSize == 0 && buffer->size > 0, "callbackwrapper: empty buffer returned");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002338
2339 buffer->size = actualSize;
2340 } break;
2341
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002342 case AudioTrack::EVENT_STREAM_END:
Andy Hung719b46b2015-05-31 22:18:25 -07002343 // currently only occurs for offloaded callbacks
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002344 ALOGV("callbackwrapper: deliver EVENT_STREAM_END");
2345 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2346 me->mCallbackCookie, CB_EVENT_STREAM_END);
2347 break;
2348
2349 case AudioTrack::EVENT_NEW_IAUDIOTRACK :
2350 ALOGV("callbackwrapper: deliver EVENT_TEAR_DOWN");
2351 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2352 me->mCallbackCookie, CB_EVENT_TEAR_DOWN);
2353 break;
2354
Glenn Kasten421743b2015-06-01 08:18:08 -07002355 case AudioTrack::EVENT_UNDERRUN:
Andy Hung719b46b2015-05-31 22:18:25 -07002356 // This occurs when there is no data available, typically
Glenn Kasten421743b2015-06-01 08:18:08 -07002357 // when there is a failure to supply data to the AudioTrack. It can also
2358 // occur in non-offloaded mode when the audio device comes out of standby.
2359 //
Andy Hung719b46b2015-05-31 22:18:25 -07002360 // If an AudioTrack underruns it outputs silence. Since this happens suddenly
2361 // it may sound like an audible pop or glitch.
2362 //
2363 // The underrun event is sent once per track underrun; the condition is reset
2364 // when more data is sent to the AudioTrack.
Eric Laurente93cc032016-05-05 10:15:10 -07002365 ALOGD("callbackwrapper: EVENT_UNDERRUN (discarded)");
Glenn Kasten421743b2015-06-01 08:18:08 -07002366 break;
2367
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002368 default:
2369 ALOGE("received unknown event type: %d inside CallbackWrapper !", event);
Andreas Huber51c1e0e2011-04-04 11:43:40 -07002370 }
2371
Marco Nelissen6b74d672012-02-28 16:07:44 -08002372 data->unlock();
Andreas Huber20111aa2009-07-14 16:56:47 -07002373}
2374
Glenn Kastend848eb42016-03-08 13:42:11 -08002375audio_session_t MediaPlayerService::AudioOutput::getSessionId() const
Eric Laurent8c563ed2010-10-07 18:23:03 -07002376{
Andy Hungd1c74342015-07-07 16:54:23 -07002377 Mutex::Autolock lock(mLock);
Eric Laurent8c563ed2010-10-07 18:23:03 -07002378 return mSessionId;
2379}
2380
Eric Laurent6f59db12013-07-26 17:16:50 -07002381uint32_t MediaPlayerService::AudioOutput::getSampleRate() const
2382{
Andy Hungd1c74342015-07-07 16:54:23 -07002383 Mutex::Autolock lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -07002384 if (mTrack == 0) return 0;
2385 return mTrack->getSampleRate();
2386}
2387
Andy Hungf2c87b32016-04-07 19:49:29 -07002388int64_t MediaPlayerService::AudioOutput::getBufferDurationInUs() const
2389{
2390 Mutex::Autolock lock(mLock);
2391 if (mTrack == 0) {
2392 return 0;
2393 }
2394 int64_t duration;
2395 if (mTrack->getBufferDurationInUs(&duration) != OK) {
2396 return 0;
2397 }
2398 return duration;
2399}
2400
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002401////////////////////////////////////////////////////////////////////////////////
2402
2403struct CallbackThread : public Thread {
2404 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
2405 MediaPlayerBase::AudioSink::AudioCallback cb,
2406 void *cookie);
2407
2408protected:
2409 virtual ~CallbackThread();
2410
2411 virtual bool threadLoop();
2412
2413private:
2414 wp<MediaPlayerBase::AudioSink> mSink;
2415 MediaPlayerBase::AudioSink::AudioCallback mCallback;
2416 void *mCookie;
2417 void *mBuffer;
2418 size_t mBufferSize;
2419
2420 CallbackThread(const CallbackThread &);
2421 CallbackThread &operator=(const CallbackThread &);
2422};
2423
2424CallbackThread::CallbackThread(
2425 const wp<MediaPlayerBase::AudioSink> &sink,
2426 MediaPlayerBase::AudioSink::AudioCallback cb,
2427 void *cookie)
2428 : mSink(sink),
2429 mCallback(cb),
2430 mCookie(cookie),
2431 mBuffer(NULL),
2432 mBufferSize(0) {
2433}
2434
2435CallbackThread::~CallbackThread() {
2436 if (mBuffer) {
2437 free(mBuffer);
2438 mBuffer = NULL;
2439 }
2440}
2441
2442bool CallbackThread::threadLoop() {
2443 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
2444 if (sink == NULL) {
2445 return false;
2446 }
2447
2448 if (mBuffer == NULL) {
2449 mBufferSize = sink->bufferSize();
2450 mBuffer = malloc(mBufferSize);
2451 }
2452
2453 size_t actualSize =
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002454 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie,
2455 MediaPlayerBase::AudioSink::CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002456
2457 if (actualSize > 0) {
2458 sink->write(mBuffer, actualSize);
Andy Hunga31335a2014-08-20 17:37:59 -07002459 // Could return false on sink->write() error or short count.
2460 // Not necessarily appropriate but would work for AudioCache behavior.
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002461 }
2462
2463 return true;
2464}
2465
2466////////////////////////////////////////////////////////////////////////////////
2467
Gloria Wang7cf180c2011-02-19 18:37:57 -08002468void MediaPlayerService::addBatteryData(uint32_t params)
2469{
2470 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002471
2472 int32_t time = systemTime() / 1000000L;
2473
2474 // change audio output devices. This notification comes from AudioFlinger
2475 if ((params & kBatteryDataSpeakerOn)
2476 || (params & kBatteryDataOtherAudioDeviceOn)) {
2477
2478 int deviceOn[NUM_AUDIO_DEVICES];
2479 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2480 deviceOn[i] = 0;
2481 }
2482
2483 if ((params & kBatteryDataSpeakerOn)
2484 && (params & kBatteryDataOtherAudioDeviceOn)) {
2485 deviceOn[SPEAKER_AND_OTHER] = 1;
2486 } else if (params & kBatteryDataSpeakerOn) {
2487 deviceOn[SPEAKER] = 1;
2488 } else {
2489 deviceOn[OTHER_AUDIO_DEVICE] = 1;
2490 }
2491
2492 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2493 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
2494
2495 if (mBatteryAudio.refCount > 0) { // if playing audio
2496 if (!deviceOn[i]) {
2497 mBatteryAudio.lastTime[i] += time;
2498 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2499 mBatteryAudio.lastTime[i] = 0;
2500 } else {
2501 mBatteryAudio.lastTime[i] = 0 - time;
2502 }
2503 }
2504
2505 mBatteryAudio.deviceOn[i] = deviceOn[i];
2506 }
2507 }
2508 return;
2509 }
2510
Marco Nelissenb7848f12014-12-04 08:57:56 -08002511 // an audio stream is started
Gloria Wang9ee159b2011-02-24 14:51:45 -08002512 if (params & kBatteryDataAudioFlingerStart) {
2513 // record the start time only if currently no other audio
2514 // is being played
2515 if (mBatteryAudio.refCount == 0) {
2516 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2517 if (mBatteryAudio.deviceOn[i]) {
2518 mBatteryAudio.lastTime[i] -= time;
2519 }
2520 }
2521 }
2522
2523 mBatteryAudio.refCount ++;
2524 return;
2525
2526 } else if (params & kBatteryDataAudioFlingerStop) {
2527 if (mBatteryAudio.refCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002528 ALOGW("Battery track warning: refCount is <= 0");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002529 return;
2530 }
2531
2532 // record the stop time only if currently this is the only
2533 // audio being played
2534 if (mBatteryAudio.refCount == 1) {
2535 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2536 if (mBatteryAudio.deviceOn[i]) {
2537 mBatteryAudio.lastTime[i] += time;
2538 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2539 mBatteryAudio.lastTime[i] = 0;
2540 }
2541 }
2542 }
2543
2544 mBatteryAudio.refCount --;
2545 return;
2546 }
2547
Andy Hung1afd0982016-11-08 16:13:44 -08002548 uid_t uid = IPCThreadState::self()->getCallingUid();
Gloria Wang7cf180c2011-02-19 18:37:57 -08002549 if (uid == AID_MEDIA) {
2550 return;
2551 }
2552 int index = mBatteryData.indexOfKey(uid);
Gloria Wang7cf180c2011-02-19 18:37:57 -08002553
2554 if (index < 0) { // create a new entry for this UID
2555 BatteryUsageInfo info;
2556 info.audioTotalTime = 0;
2557 info.videoTotalTime = 0;
2558 info.audioLastTime = 0;
2559 info.videoLastTime = 0;
2560 info.refCount = 0;
2561
Gloria Wang9ee159b2011-02-24 14:51:45 -08002562 if (mBatteryData.add(uid, info) == NO_MEMORY) {
Steve Block29357bc2012-01-06 19:20:56 +00002563 ALOGE("Battery track error: no memory for new app");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002564 return;
2565 }
Gloria Wang7cf180c2011-02-19 18:37:57 -08002566 }
2567
2568 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
2569
2570 if (params & kBatteryDataCodecStarted) {
2571 if (params & kBatteryDataTrackAudio) {
2572 info.audioLastTime -= time;
2573 info.refCount ++;
2574 }
2575 if (params & kBatteryDataTrackVideo) {
2576 info.videoLastTime -= time;
2577 info.refCount ++;
2578 }
2579 } else {
2580 if (info.refCount == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002581 ALOGW("Battery track warning: refCount is already 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002582 return;
2583 } else if (info.refCount < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00002584 ALOGE("Battery track error: refCount < 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002585 mBatteryData.removeItem(uid);
2586 return;
2587 }
2588
2589 if (params & kBatteryDataTrackAudio) {
2590 info.audioLastTime += time;
2591 info.refCount --;
2592 }
2593 if (params & kBatteryDataTrackVideo) {
2594 info.videoLastTime += time;
2595 info.refCount --;
2596 }
2597
2598 // no stream is being played by this UID
2599 if (info.refCount == 0) {
2600 info.audioTotalTime += info.audioLastTime;
2601 info.audioLastTime = 0;
2602 info.videoTotalTime += info.videoLastTime;
2603 info.videoLastTime = 0;
2604 }
2605 }
2606}
2607
2608status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
2609 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002610
2611 // audio output devices usage
2612 int32_t time = systemTime() / 1000000L; //in ms
2613 int32_t totalTime;
2614
2615 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2616 totalTime = mBatteryAudio.totalTime[i];
2617
2618 if (mBatteryAudio.deviceOn[i]
2619 && (mBatteryAudio.lastTime[i] != 0)) {
2620 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
2621 totalTime += tmpTime;
2622 }
2623
2624 reply->writeInt32(totalTime);
2625 // reset the total time
2626 mBatteryAudio.totalTime[i] = 0;
2627 }
2628
2629 // codec usage
Gloria Wang7cf180c2011-02-19 18:37:57 -08002630 BatteryUsageInfo info;
2631 int size = mBatteryData.size();
2632
2633 reply->writeInt32(size);
2634 int i = 0;
2635
2636 while (i < size) {
2637 info = mBatteryData.valueAt(i);
2638
2639 reply->writeInt32(mBatteryData.keyAt(i)); //UID
2640 reply->writeInt32(info.audioTotalTime);
2641 reply->writeInt32(info.videoTotalTime);
2642
2643 info.audioTotalTime = 0;
2644 info.videoTotalTime = 0;
2645
2646 // remove the UID entry where no stream is being played
2647 if (info.refCount <= 0) {
2648 mBatteryData.removeItemsAt(i);
2649 size --;
2650 i --;
2651 }
2652 i++;
2653 }
2654 return NO_ERROR;
2655}
nikoa64c8c72009-07-20 15:07:26 -07002656} // namespace android