blob: cdae4561c76620c3d8b987c5cace9dbef1154050 [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>
Ruben Brunk99e69712015-05-26 17:25:07 -070063#include <mediautils/BatteryNotifier.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080064
Andy Hung53541292016-04-13 16:48:51 -070065#include <memunreachable/memunreachable.h>
Dima Zavin64760242011-05-11 14:15:23 -070066#include <system/audio.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070067
Gloria Wang7cf180c2011-02-19 18:37:57 -080068#include <private/android_filesystem_config.h>
69
James Dong559bf282012-03-28 10:29:14 -070070#include "ActivityManager.h"
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080071#include "MediaRecorderClient.h"
72#include "MediaPlayerService.h"
73#include "MetadataRetrieverClient.h"
John Grossman44a7e422012-06-21 17:29:24 -070074#include "MediaPlayerFactory.h"
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080075
Nicolas Catania14d27472009-07-13 14:37:49 -070076#include "TestPlayerStub.h"
Andreas Huberf9334412010-12-15 15:17:42 -080077#include "nuplayer/NuPlayerDriver.h"
Andreas Huber20111aa2009-07-14 16:56:47 -070078
Andreas Huber20111aa2009-07-14 16:56:47 -070079#include <OMX.h>
Nicolas Catania14d27472009-07-13 14:37:49 -070080
Andreas Huber59451f82012-09-18 10:36:32 -070081#include "HDCP.h"
Andreas Huberb7319a72013-05-29 14:20:52 -070082#include "HTTPBase.h"
Andreas Huber35213f12012-08-29 11:41:50 -070083#include "RemoteDisplay.h"
Andreas Hubered3e3e02012-03-26 11:13:27 -070084
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070085namespace {
nikoa64c8c72009-07-20 15:07:26 -070086using android::media::Metadata;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070087using android::status_t;
88using android::OK;
89using android::BAD_VALUE;
90using android::NOT_ENOUGH_DATA;
91using android::Parcel;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070092
93// Max number of entries in the filter.
94const int kMaxFilterSize = 64; // I pulled that out of thin air.
95
Andy Hungff874dc2016-04-11 16:49:09 -070096const float kMaxRequiredSpeed = 8.0f; // for PCM tracks allow up to 8x speedup.
97
nikoa64c8c72009-07-20 15:07:26 -070098// FIXME: Move all the metadata related function in the Metadata.cpp
nikod608a812009-07-16 16:39:53 -070099
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700100
101// Unmarshall a filter from a Parcel.
102// Filter format in a parcel:
103//
104// 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
105// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
106// | number of entries (n) |
107// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
108// | metadata type 1 |
109// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
110// | metadata type 2 |
111// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
112// ....
113// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
114// | metadata type n |
115// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
116//
117// @param p Parcel that should start with a filter.
118// @param[out] filter On exit contains the list of metadata type to be
119// filtered.
120// @param[out] status On exit contains the status code to be returned.
121// @return true if the parcel starts with a valid filter.
122bool unmarshallFilter(const Parcel& p,
nikoa64c8c72009-07-20 15:07:26 -0700123 Metadata::Filter *filter,
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700124 status_t *status)
125{
Nicolas Catania48290382009-07-10 13:53:06 -0700126 int32_t val;
127 if (p.readInt32(&val) != OK)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700128 {
Steve Block29357bc2012-01-06 19:20:56 +0000129 ALOGE("Failed to read filter's length");
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700130 *status = NOT_ENOUGH_DATA;
131 return false;
132 }
133
Nicolas Catania48290382009-07-10 13:53:06 -0700134 if( val > kMaxFilterSize || val < 0)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700135 {
Steve Block29357bc2012-01-06 19:20:56 +0000136 ALOGE("Invalid filter len %d", val);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700137 *status = BAD_VALUE;
138 return false;
139 }
140
Nicolas Catania48290382009-07-10 13:53:06 -0700141 const size_t num = val;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700142
143 filter->clear();
Nicolas Catania48290382009-07-10 13:53:06 -0700144 filter->setCapacity(num);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700145
nikoa64c8c72009-07-20 15:07:26 -0700146 size_t size = num * sizeof(Metadata::Type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700147
Nicolas Catania48290382009-07-10 13:53:06 -0700148
149 if (p.dataAvail() < size)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700150 {
Andy Hung833b4752016-04-04 17:15:48 -0700151 ALOGE("Filter too short expected %zu but got %zu", size, p.dataAvail());
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700152 *status = NOT_ENOUGH_DATA;
153 return false;
154 }
155
nikoa64c8c72009-07-20 15:07:26 -0700156 const Metadata::Type *data =
157 static_cast<const Metadata::Type*>(p.readInplace(size));
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700158
Nicolas Catania48290382009-07-10 13:53:06 -0700159 if (NULL == data)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700160 {
Steve Block29357bc2012-01-06 19:20:56 +0000161 ALOGE("Filter had no data");
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700162 *status = BAD_VALUE;
163 return false;
164 }
165
166 // TODO: The stl impl of vector would be more efficient here
167 // because it degenerates into a memcpy on pod types. Try to
168 // replace later or use stl::set.
Nicolas Catania48290382009-07-10 13:53:06 -0700169 for (size_t i = 0; i < num; ++i)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700170 {
Nicolas Catania48290382009-07-10 13:53:06 -0700171 filter->add(*data);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700172 ++data;
173 }
174 *status = OK;
175 return true;
176}
177
Nicolas Catania48290382009-07-10 13:53:06 -0700178// @param filter Of metadata type.
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700179// @param val To be searched.
180// @return true if a match was found.
nikoa64c8c72009-07-20 15:07:26 -0700181bool findMetadata(const Metadata::Filter& filter, const int32_t val)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700182{
183 // Deal with empty and ANY right away
184 if (filter.isEmpty()) return false;
nikoa64c8c72009-07-20 15:07:26 -0700185 if (filter[0] == Metadata::kAny) return true;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700186
Nicolas Catania48290382009-07-10 13:53:06 -0700187 return filter.indexOf(val) >= 0;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700188}
189
190} // anonymous namespace
191
192
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700193namespace {
194using android::Parcel;
195using android::String16;
196
197// marshalling tag indicating flattened utf16 tags
198// keep in sync with frameworks/base/media/java/android/media/AudioAttributes.java
199const int32_t kAudioAttributesMarshallTagFlattenTags = 1;
200
201// Audio attributes format in a parcel:
202//
203// 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
204// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
205// | usage |
206// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
207// | content_type |
208// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Hyejin Kim4f418f92014-09-05 15:50:03 +0900209// | source |
210// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700211// | flags |
212// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
213// | kAudioAttributesMarshallTagFlattenTags | // ignore tags if not found
214// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
215// | flattened tags in UTF16 |
216// | ... |
217// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
218//
219// @param p Parcel that contains audio attributes.
220// @param[out] attributes On exit points to an initialized audio_attributes_t structure
221// @param[out] status On exit contains the status code to be returned.
222void unmarshallAudioAttributes(const Parcel& parcel, audio_attributes_t *attributes)
223{
224 attributes->usage = (audio_usage_t) parcel.readInt32();
225 attributes->content_type = (audio_content_type_t) parcel.readInt32();
Hyejin Kim4f418f92014-09-05 15:50:03 +0900226 attributes->source = (audio_source_t) parcel.readInt32();
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700227 attributes->flags = (audio_flags_mask_t) parcel.readInt32();
228 const bool hasFlattenedTag = (parcel.readInt32() == kAudioAttributesMarshallTagFlattenTags);
229 if (hasFlattenedTag) {
230 // the tags are UTF16, convert to UTF8
231 String16 tags = parcel.readString16();
232 ssize_t realTagSize = utf16_to_utf8_length(tags.string(), tags.size());
233 if (realTagSize <= 0) {
234 strcpy(attributes->tags, "");
235 } else {
236 // copy the flattened string into the attributes as the destination for the conversion:
237 // copying array size -1, array for tags was calloc'd, no need to NULL-terminate it
238 size_t tagSize = realTagSize > AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 ?
239 AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 : realTagSize;
Sergio Giro1d3f4272016-06-28 18:24:52 +0100240 utf16_to_utf8(tags.string(), tagSize, attributes->tags,
241 sizeof(attributes->tags) / sizeof(attributes->tags[0]));
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700242 }
243 } else {
244 ALOGE("unmarshallAudioAttributes() received unflattened tags, ignoring tag values");
245 strcpy(attributes->tags, "");
246 }
247}
248} // anonymous namespace
249
250
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800251namespace android {
252
Marco Nelissenf09611f2015-02-13 14:12:42 -0800253extern ALooperRoster gLooperRoster;
254
255
Dave Burked681bbb2011-08-30 14:39:17 +0100256static bool checkPermission(const char* permissionString) {
Dave Burked681bbb2011-08-30 14:39:17 +0100257 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
258 bool ok = checkCallingPermission(String16(permissionString));
Steve Block29357bc2012-01-06 19:20:56 +0000259 if (!ok) ALOGE("Request requires %s", permissionString);
Dave Burked681bbb2011-08-30 14:39:17 +0100260 return ok;
261}
262
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800263// 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 -0800264/* static */ int MediaPlayerService::AudioOutput::mMinBufferCount = 4;
265/* static */ bool MediaPlayerService::AudioOutput::mIsOnEmulator = false;
266
267void MediaPlayerService::instantiate() {
268 defaultServiceManager()->addService(
269 String16("media.player"), new MediaPlayerService());
270}
271
272MediaPlayerService::MediaPlayerService()
273{
Steve Block3856b092011-10-20 11:56:00 +0100274 ALOGV("MediaPlayerService created");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800275 mNextConnId = 1;
Gloria Wang9ee159b2011-02-24 14:51:45 -0800276
277 mBatteryAudio.refCount = 0;
278 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
279 mBatteryAudio.deviceOn[i] = 0;
280 mBatteryAudio.lastTime[i] = 0;
281 mBatteryAudio.totalTime[i] = 0;
282 }
283 // speaker is on by default
284 mBatteryAudio.deviceOn[SPEAKER] = 1;
John Grossman44a7e422012-06-21 17:29:24 -0700285
Chong Zhang0b30fd42014-07-23 14:46:05 -0700286 // reset battery stats
287 // if the mediaserver has crashed, battery stats could be left
288 // in bad state, reset the state upon service start.
Wei Jia3f273d12015-11-24 09:06:49 -0800289 BatteryNotifier::getInstance().noteResetVideo();
Chong Zhang0b30fd42014-07-23 14:46:05 -0700290
John Grossman44a7e422012-06-21 17:29:24 -0700291 MediaPlayerFactory::registerBuiltinFactories();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800292}
293
294MediaPlayerService::~MediaPlayerService()
295{
Steve Block3856b092011-10-20 11:56:00 +0100296 ALOGV("MediaPlayerService destroyed");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800297}
298
Svet Ganovbe71aa22015-04-28 12:06:02 -0700299sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(const String16 &opPackageName)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800300{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800301 pid_t pid = IPCThreadState::self()->getCallingPid();
Svet Ganovbe71aa22015-04-28 12:06:02 -0700302 sp<MediaRecorderClient> recorder = new MediaRecorderClient(this, pid, opPackageName);
Gloria Wangdac6a312009-10-29 15:46:37 -0700303 wp<MediaRecorderClient> w = recorder;
304 Mutex::Autolock lock(mLock);
305 mMediaRecorderClients.add(w);
Steve Block3856b092011-10-20 11:56:00 +0100306 ALOGV("Create new media recorder client from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800307 return recorder;
308}
309
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -0700310void MediaPlayerService::removeMediaRecorderClient(const wp<MediaRecorderClient>& client)
Gloria Wangdac6a312009-10-29 15:46:37 -0700311{
312 Mutex::Autolock lock(mLock);
313 mMediaRecorderClients.remove(client);
Steve Block3856b092011-10-20 11:56:00 +0100314 ALOGV("Delete media recorder client");
Gloria Wangdac6a312009-10-29 15:46:37 -0700315}
316
Glenn Kastenf37971f2012-02-03 11:06:53 -0800317sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800318{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800319 pid_t pid = IPCThreadState::self()->getCallingPid();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800320 sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
Steve Block3856b092011-10-20 11:56:00 +0100321 ALOGV("Create new media retriever from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800322 return retriever;
323}
324
Glenn Kastenf37971f2012-02-03 11:06:53 -0800325sp<IMediaPlayer> MediaPlayerService::create(const sp<IMediaPlayerClient>& client,
Glenn Kastend848eb42016-03-08 13:42:11 -0800326 audio_session_t audioSessionId)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800327{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800328 pid_t pid = IPCThreadState::self()->getCallingPid();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800329 int32_t connId = android_atomic_inc(&mNextConnId);
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700330
331 sp<Client> c = new Client(
332 this, pid, connId, client, audioSessionId,
333 IPCThreadState::self()->getCallingUid());
334
Steve Block3856b092011-10-20 11:56:00 +0100335 ALOGV("Create new client(%d) from pid %d, uid %d, ", connId, pid,
Dave Burked681bbb2011-08-30 14:39:17 +0100336 IPCThreadState::self()->getCallingUid());
337
338 wp<Client> w = c;
339 {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800340 Mutex::Autolock lock(mLock);
341 mClients.add(w);
342 }
Andreas Hubere2b10282010-11-23 11:41:34 -0800343 return c;
344}
345
Lajos Molnar1381d4b2014-08-07 15:18:35 -0700346sp<IMediaCodecList> MediaPlayerService::getCodecList() const {
347 return MediaCodecList::getLocalInstance();
348}
349
Marco Nelissen260e56c2016-01-28 21:41:25 +0000350sp<IOMX> MediaPlayerService::getOMX() {
Marco Nelissen1900e772016-02-02 16:12:16 -0800351 ALOGI("MediaPlayerService::getOMX");
Marco Nelissen260e56c2016-01-28 21:41:25 +0000352 Mutex::Autolock autoLock(mLock);
353
354 if (mOMX.get() == NULL) {
355 mOMX = new OMX;
356 }
357
358 return mOMX;
359}
360
Andreas Huber279dcd82013-01-30 10:41:25 -0800361sp<IHDCP> MediaPlayerService::makeHDCP(bool createEncryptionModule) {
362 return new HDCP(createEncryptionModule);
Andreas Huber59451f82012-09-18 10:36:32 -0700363}
364
Jeff Brown2013a542012-09-04 21:38:42 -0700365sp<IRemoteDisplay> MediaPlayerService::listenForRemoteDisplay(
Svet Ganovbe71aa22015-04-28 12:06:02 -0700366 const String16 &opPackageName,
Jeff Brown2013a542012-09-04 21:38:42 -0700367 const sp<IRemoteDisplayClient>& client, const String8& iface) {
Jeff Brownaba33d52012-09-07 17:38:58 -0700368 if (!checkPermission("android.permission.CONTROL_WIFI_DISPLAY")) {
369 return NULL;
370 }
371
Svet Ganovbe71aa22015-04-28 12:06:02 -0700372 return new RemoteDisplay(opPackageName, client, iface.string());
Jeff Brown2013a542012-09-04 21:38:42 -0700373}
374
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800375status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
376{
377 const size_t SIZE = 256;
378 char buffer[SIZE];
379 String8 result;
380
381 result.append(" AudioOutput\n");
382 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n",
383 mStreamType, mLeftVolume, mRightVolume);
384 result.append(buffer);
385 snprintf(buffer, 255, " msec per frame(%f), latency (%d)\n",
Eric Laurentdb354e52012-03-05 17:27:11 -0800386 mMsecsPerFrame, (mTrack != 0) ? mTrack->latency() : -1);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800387 result.append(buffer);
Eric Laurent2beeb502010-07-16 07:43:46 -0700388 snprintf(buffer, 255, " aux effect id(%d), send level (%f)\n",
389 mAuxEffectId, mSendLevel);
390 result.append(buffer);
391
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800392 ::write(fd, result.string(), result.size());
393 if (mTrack != 0) {
394 mTrack->dump(fd, args);
395 }
396 return NO_ERROR;
397}
398
Lajos Molnar6d339f12015-04-17 16:15:53 -0700399status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800400{
401 const size_t SIZE = 256;
402 char buffer[SIZE];
403 String8 result;
404 result.append(" Client\n");
405 snprintf(buffer, 255, " pid(%d), connId(%d), status(%d), looping(%s)\n",
406 mPid, mConnId, mStatus, mLoop?"true": "false");
407 result.append(buffer);
408 write(fd, result.string(), result.size());
Andreas Hubera0b1d4b2011-06-07 15:52:25 -0700409 if (mPlayer != NULL) {
410 mPlayer->dump(fd, args);
411 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800412 if (mAudioOutput != 0) {
413 mAudioOutput->dump(fd, args);
414 }
415 write(fd, "\n", 1);
416 return NO_ERROR;
417}
418
Marco Nelissenf09611f2015-02-13 14:12:42 -0800419/**
420 * The only arguments this understands right now are -c, -von and -voff,
421 * which are parsed by ALooperRoster::dump()
422 */
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800423status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
424{
425 const size_t SIZE = 256;
426 char buffer[SIZE];
427 String8 result;
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530428 SortedVector< sp<Client> > clients; //to serialise the mutex unlock & client destruction.
429 SortedVector< sp<MediaRecorderClient> > mediaRecorderClients;
430
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800431 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
432 snprintf(buffer, SIZE, "Permission Denial: "
433 "can't dump MediaPlayerService from pid=%d, uid=%d\n",
434 IPCThreadState::self()->getCallingPid(),
435 IPCThreadState::self()->getCallingUid());
436 result.append(buffer);
437 } else {
438 Mutex::Autolock lock(mLock);
439 for (int i = 0, n = mClients.size(); i < n; ++i) {
440 sp<Client> c = mClients[i].promote();
441 if (c != 0) c->dump(fd, args);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530442 clients.add(c);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800443 }
James Dongb9141222010-07-08 11:16:11 -0700444 if (mMediaRecorderClients.size() == 0) {
445 result.append(" No media recorder client\n\n");
446 } else {
447 for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
448 sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
James Donge579e282011-10-18 22:29:20 -0700449 if (c != 0) {
450 snprintf(buffer, 255, " MediaRecorderClient pid(%d)\n", c->mPid);
451 result.append(buffer);
452 write(fd, result.string(), result.size());
453 result = "\n";
454 c->dump(fd, args);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530455 mediaRecorderClients.add(c);
James Donge579e282011-10-18 22:29:20 -0700456 }
James Dongb9141222010-07-08 11:16:11 -0700457 }
Gloria Wangdac6a312009-10-29 15:46:37 -0700458 }
459
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800460 result.append(" Files opened and/or mapped:\n");
Marco Nelissenf09611f2015-02-13 14:12:42 -0800461 snprintf(buffer, SIZE, "/proc/%d/maps", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800462 FILE *f = fopen(buffer, "r");
463 if (f) {
464 while (!feof(f)) {
465 fgets(buffer, SIZE, f);
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700466 if (strstr(buffer, " /storage/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800467 strstr(buffer, " /system/sounds/") ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700468 strstr(buffer, " /data/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800469 strstr(buffer, " /system/media/")) {
470 result.append(" ");
471 result.append(buffer);
472 }
473 }
474 fclose(f);
475 } else {
476 result.append("couldn't open ");
477 result.append(buffer);
478 result.append("\n");
479 }
480
Marco Nelissenf09611f2015-02-13 14:12:42 -0800481 snprintf(buffer, SIZE, "/proc/%d/fd", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800482 DIR *d = opendir(buffer);
483 if (d) {
484 struct dirent *ent;
485 while((ent = readdir(d)) != NULL) {
486 if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
Marco Nelissenf09611f2015-02-13 14:12:42 -0800487 snprintf(buffer, SIZE, "/proc/%d/fd/%s", getpid(), ent->d_name);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800488 struct stat s;
489 if (lstat(buffer, &s) == 0) {
490 if ((s.st_mode & S_IFMT) == S_IFLNK) {
491 char linkto[256];
492 int len = readlink(buffer, linkto, sizeof(linkto));
493 if(len > 0) {
494 if(len > 255) {
495 linkto[252] = '.';
496 linkto[253] = '.';
497 linkto[254] = '.';
498 linkto[255] = 0;
499 } else {
500 linkto[len] = 0;
501 }
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700502 if (strstr(linkto, "/storage/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800503 strstr(linkto, "/system/sounds/") == linkto ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700504 strstr(linkto, "/data/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800505 strstr(linkto, "/system/media/") == linkto) {
506 result.append(" ");
507 result.append(buffer);
508 result.append(" -> ");
509 result.append(linkto);
510 result.append("\n");
511 }
512 }
513 } else {
514 result.append(" unexpected type for ");
515 result.append(buffer);
516 result.append("\n");
517 }
518 }
519 }
520 }
521 closedir(d);
522 } else {
523 result.append("couldn't open ");
524 result.append(buffer);
525 result.append("\n");
526 }
527
Marco Nelissenf09611f2015-02-13 14:12:42 -0800528 gLooperRoster.dump(fd, args);
529
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800530 bool dumpMem = false;
Andy Hung53541292016-04-13 16:48:51 -0700531 bool unreachableMemory = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800532 for (size_t i = 0; i < args.size(); i++) {
533 if (args[i] == String16("-m")) {
534 dumpMem = true;
Andy Hung53541292016-04-13 16:48:51 -0700535 } else if (args[i] == String16("--unreachable")) {
536 unreachableMemory = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800537 }
538 }
539 if (dumpMem) {
Andy Hung07b745e2016-05-23 16:21:07 -0700540 result.append("\nDumping memory:\n");
541 std::string s = dumpMemoryAddresses(100 /* limit */);
542 result.append(s.c_str(), s.size());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800543 }
Andy Hung53541292016-04-13 16:48:51 -0700544 if (unreachableMemory) {
545 result.append("\nDumping unreachable memory:\n");
546 // TODO - should limit be an argument parameter?
547 std::string s = GetUnreachableMemoryString(true /* contents */, 10000 /* limit */);
548 result.append(s.c_str(), s.size());
549 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800550 }
551 write(fd, result.string(), result.size());
552 return NO_ERROR;
553}
554
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -0700555void MediaPlayerService::removeClient(const wp<Client>& client)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800556{
557 Mutex::Autolock lock(mLock);
558 mClients.remove(client);
559}
560
Robert Shihee0a0e32016-08-16 16:50:54 -0700561bool MediaPlayerService::hasClient(wp<Client> client)
562{
563 Mutex::Autolock lock(mLock);
564 return mClients.indexOf(client) != NAME_NOT_FOUND;
565}
566
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700567MediaPlayerService::Client::Client(
568 const sp<MediaPlayerService>& service, pid_t pid,
569 int32_t connId, const sp<IMediaPlayerClient>& client,
Glenn Kastend848eb42016-03-08 13:42:11 -0800570 audio_session_t audioSessionId, uid_t uid)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800571{
Steve Block3856b092011-10-20 11:56:00 +0100572 ALOGV("Client(%d) constructor", connId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800573 mPid = pid;
574 mConnId = connId;
575 mService = service;
576 mClient = client;
577 mLoop = false;
578 mStatus = NO_INIT;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700579 mAudioSessionId = audioSessionId;
Andy Hung1afd0982016-11-08 16:13:44 -0800580 mUid = uid;
John Grossmanc795b642012-02-22 15:38:35 -0800581 mRetransmitEndpointValid = false;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700582 mAudioAttributes = NULL;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700583
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800584#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000585 ALOGD("create Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800586 mAntagonizer = new Antagonizer(notify, this);
587#endif
588}
589
590MediaPlayerService::Client::~Client()
591{
Steve Block3856b092011-10-20 11:56:00 +0100592 ALOGV("Client(%d) destructor pid = %d", mConnId, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800593 mAudioOutput.clear();
594 wp<Client> client(this);
595 disconnect();
596 mService->removeClient(client);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700597 if (mAudioAttributes != NULL) {
598 free(mAudioAttributes);
599 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800600}
601
602void MediaPlayerService::Client::disconnect()
603{
Steve Block3856b092011-10-20 11:56:00 +0100604 ALOGV("disconnect(%d) from pid %d", mConnId, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800605 // grab local reference and clear main reference to prevent future
606 // access to object
607 sp<MediaPlayerBase> p;
608 {
609 Mutex::Autolock l(mLock);
610 p = mPlayer;
beanzdcfefde2012-11-05 09:51:43 +0800611 mClient.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800612 }
Andreas Huber20111aa2009-07-14 16:56:47 -0700613
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800614 mPlayer.clear();
615
616 // clear the notification to prevent callbacks to dead client
617 // and reset the player. We assume the player will serialize
618 // access to itself if necessary.
619 if (p != 0) {
620 p->setNotifyCallback(0, 0);
621#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000622 ALOGD("kill Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800623 mAntagonizer->kill();
624#endif
625 p->reset();
626 }
627
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700628 disconnectNativeWindow();
629
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800630 IPCThreadState::self()->flushCommands();
631}
632
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800633sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
634{
635 // determine if we have the right player type
636 sp<MediaPlayerBase> p = mPlayer;
637 if ((p != NULL) && (p->playerType() != playerType)) {
Steve Block3856b092011-10-20 11:56:00 +0100638 ALOGV("delete player");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800639 p.clear();
640 }
641 if (p == NULL) {
Ronghua Wu68845c12015-07-21 09:50:48 -0700642 p = MediaPlayerFactory::createPlayer(playerType, this, notify, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800643 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700644
Jason Simmonsdb29e522011-08-12 13:46:55 -0700645 if (p != NULL) {
Andy Hung1afd0982016-11-08 16:13:44 -0800646 p->setUID(mUid);
Jason Simmonsdb29e522011-08-12 13:46:55 -0700647 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700648
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800649 return p;
650}
651
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700652MediaPlayerService::Client::ServiceDeathNotifier::ServiceDeathNotifier(
653 const sp<IBinder>& service,
654 const sp<MediaPlayerBase>& listener,
655 int which) {
656 mService = service;
657 mListener = listener;
658 mWhich = which;
659}
660
661MediaPlayerService::Client::ServiceDeathNotifier::~ServiceDeathNotifier() {
662 mService->unlinkToDeath(this);
663}
664
665void MediaPlayerService::Client::ServiceDeathNotifier::binderDied(const wp<IBinder>& /*who*/) {
666 sp<MediaPlayerBase> listener = mListener.promote();
667 if (listener != NULL) {
668 listener->sendEvent(MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED, mWhich);
669 } else {
670 ALOGW("listener for process %d death is gone", mWhich);
671 }
672}
673
John Grossmanc795b642012-02-22 15:38:35 -0800674sp<MediaPlayerBase> MediaPlayerService::Client::setDataSource_pre(
675 player_type playerType)
676{
677 ALOGV("player type = %d", playerType);
678
679 // create the right type of player
680 sp<MediaPlayerBase> p = createPlayer(playerType);
681 if (p == NULL) {
682 return p;
683 }
684
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700685 sp<IServiceManager> sm = defaultServiceManager();
686 sp<IBinder> binder = sm->getService(String16("media.extractor"));
Marco Nelissen1b5a7ee2016-09-30 13:54:30 -0700687 if (binder == NULL) {
688 ALOGE("extractor service not available");
689 return NULL;
690 }
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700691 mExtractorDeathListener = new ServiceDeathNotifier(binder, p, MEDIAEXTRACTOR_PROCESS_DEATH);
692 binder->linkToDeath(mExtractorDeathListener);
693
694 binder = sm->getService(String16("media.codec"));
Marco Nelissen1b5a7ee2016-09-30 13:54:30 -0700695 if (binder == NULL) {
696 ALOGE("codec service not available");
697 return NULL;
698 }
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700699 mCodecDeathListener = new ServiceDeathNotifier(binder, p, MEDIACODEC_PROCESS_DEATH);
700 binder->linkToDeath(mCodecDeathListener);
701
John Grossmanc795b642012-02-22 15:38:35 -0800702 if (!p->hardwareOutput()) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -0700703 Mutex::Autolock l(mLock);
Marco Nelissend457c972014-02-11 08:47:07 -0800704 mAudioOutput = new AudioOutput(mAudioSessionId, IPCThreadState::self()->getCallingUid(),
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700705 mPid, mAudioAttributes);
John Grossmanc795b642012-02-22 15:38:35 -0800706 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
707 }
708
709 return p;
710}
711
712void MediaPlayerService::Client::setDataSource_post(
713 const sp<MediaPlayerBase>& p,
714 status_t status)
715{
716 ALOGV(" setDataSource");
717 mStatus = status;
718 if (mStatus != OK) {
719 ALOGE(" error: %d", mStatus);
720 return;
721 }
722
723 // Set the re-transmission endpoint if one was chosen.
724 if (mRetransmitEndpointValid) {
725 mStatus = p->setRetransmitEndpoint(&mRetransmitEndpoint);
726 if (mStatus != NO_ERROR) {
727 ALOGE("setRetransmitEndpoint error: %d", mStatus);
728 }
729 }
730
731 if (mStatus == OK) {
732 mPlayer = p;
733 }
734}
735
Andreas Huber2db84552010-01-28 11:19:57 -0800736status_t MediaPlayerService::Client::setDataSource(
Andreas Huber1b86fe02014-01-29 11:13:26 -0800737 const sp<IMediaHTTPService> &httpService,
738 const char *url,
739 const KeyedVector<String8, String8> *headers)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800740{
Steve Block3856b092011-10-20 11:56:00 +0100741 ALOGV("setDataSource(%s)", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800742 if (url == NULL)
743 return UNKNOWN_ERROR;
744
Dave Burked681bbb2011-08-30 14:39:17 +0100745 if ((strncmp(url, "http://", 7) == 0) ||
746 (strncmp(url, "https://", 8) == 0) ||
747 (strncmp(url, "rtsp://", 7) == 0)) {
748 if (!checkPermission("android.permission.INTERNET")) {
749 return PERMISSION_DENIED;
750 }
751 }
752
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800753 if (strncmp(url, "content://", 10) == 0) {
754 // get a filedescriptor for the content Uri and
755 // pass it to the setDataSource(fd) method
756
757 String16 url16(url);
758 int fd = android::openContentProviderFile(url16);
759 if (fd < 0)
760 {
Steve Block29357bc2012-01-06 19:20:56 +0000761 ALOGE("Couldn't open fd for %s", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800762 return UNKNOWN_ERROR;
763 }
764 setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
765 close(fd);
766 return mStatus;
767 } else {
John Grossman44a7e422012-06-21 17:29:24 -0700768 player_type playerType = MediaPlayerFactory::getPlayerType(this, url);
John Grossmanc795b642012-02-22 15:38:35 -0800769 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
770 if (p == NULL) {
771 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800772 }
773
Andreas Huber1b86fe02014-01-29 11:13:26 -0800774 setDataSource_post(p, p->setDataSource(httpService, url, headers));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800775 return mStatus;
776 }
777}
778
779status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
780{
Marco Nelissen83b0fd92015-09-16 13:48:07 -0700781 ALOGV("setDataSource fd=%d (%s), offset=%lld, length=%lld",
782 fd, nameForFd(fd).c_str(), (long long) offset, (long long) length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800783 struct stat sb;
784 int ret = fstat(fd, &sb);
785 if (ret != 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000786 ALOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800787 return UNKNOWN_ERROR;
788 }
789
Andy Hung833b4752016-04-04 17:15:48 -0700790 ALOGV("st_dev = %llu", static_cast<unsigned long long>(sb.st_dev));
Steve Block3856b092011-10-20 11:56:00 +0100791 ALOGV("st_mode = %u", sb.st_mode);
Mark Salyzyn77342f72014-06-18 16:31:32 -0700792 ALOGV("st_uid = %lu", static_cast<unsigned long>(sb.st_uid));
793 ALOGV("st_gid = %lu", static_cast<unsigned long>(sb.st_gid));
Andy Hung833b4752016-04-04 17:15:48 -0700794 ALOGV("st_size = %llu", static_cast<unsigned long long>(sb.st_size));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800795
796 if (offset >= sb.st_size) {
Steve Block29357bc2012-01-06 19:20:56 +0000797 ALOGE("offset error");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800798 return UNKNOWN_ERROR;
799 }
800 if (offset + length > sb.st_size) {
801 length = sb.st_size - offset;
Andy Hung833b4752016-04-04 17:15:48 -0700802 ALOGV("calculated length = %lld", (long long)length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800803 }
804
John Grossman44a7e422012-06-21 17:29:24 -0700805 player_type playerType = MediaPlayerFactory::getPlayerType(this,
806 fd,
807 offset,
808 length);
John Grossmanc795b642012-02-22 15:38:35 -0800809 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
810 if (p == NULL) {
811 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800812 }
813
814 // now set data source
John Grossmanc795b642012-02-22 15:38:35 -0800815 setDataSource_post(p, p->setDataSource(fd, offset, length));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800816 return mStatus;
817}
818
Andreas Hubere2b10282010-11-23 11:41:34 -0800819status_t MediaPlayerService::Client::setDataSource(
820 const sp<IStreamSource> &source) {
821 // create the right type of player
John Grossman44a7e422012-06-21 17:29:24 -0700822 player_type playerType = MediaPlayerFactory::getPlayerType(this, source);
John Grossmanc795b642012-02-22 15:38:35 -0800823 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
Andreas Hubere2b10282010-11-23 11:41:34 -0800824 if (p == NULL) {
825 return NO_INIT;
826 }
827
Andreas Hubere2b10282010-11-23 11:41:34 -0800828 // now set data source
John Grossmanc795b642012-02-22 15:38:35 -0800829 setDataSource_post(p, p->setDataSource(source));
Andreas Hubere2b10282010-11-23 11:41:34 -0800830 return mStatus;
831}
832
Chris Watkins99f31602015-03-20 13:06:33 -0700833status_t MediaPlayerService::Client::setDataSource(
834 const sp<IDataSource> &source) {
835 sp<DataSource> dataSource = DataSource::CreateFromIDataSource(source);
836 player_type playerType = MediaPlayerFactory::getPlayerType(this, dataSource);
837 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
838 if (p == NULL) {
839 return NO_INIT;
840 }
841 // now set data source
842 setDataSource_post(p, p->setDataSource(dataSource));
843 return mStatus;
844}
845
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700846void MediaPlayerService::Client::disconnectNativeWindow() {
847 if (mConnectedWindow != NULL) {
848 status_t err = native_window_api_disconnect(mConnectedWindow.get(),
849 NATIVE_WINDOW_API_MEDIA);
850
851 if (err != OK) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000852 ALOGW("native_window_api_disconnect returned an error: %s (%d)",
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700853 strerror(-err), err);
854 }
855 }
856 mConnectedWindow.clear();
857}
858
Glenn Kasten11731182011-02-08 17:26:17 -0800859status_t MediaPlayerService::Client::setVideoSurfaceTexture(
Andy McFadden484566c2012-12-18 09:46:54 -0800860 const sp<IGraphicBufferProducer>& bufferProducer)
Glenn Kasten11731182011-02-08 17:26:17 -0800861{
Andy McFadden484566c2012-12-18 09:46:54 -0800862 ALOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, bufferProducer.get());
Glenn Kasten11731182011-02-08 17:26:17 -0800863 sp<MediaPlayerBase> p = getPlayer();
864 if (p == 0) return UNKNOWN_ERROR;
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700865
Marco Nelissenf8880202014-11-14 07:58:25 -0800866 sp<IBinder> binder(IInterface::asBinder(bufferProducer));
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700867 if (mConnectedWindowBinder == binder) {
868 return OK;
869 }
870
871 sp<ANativeWindow> anw;
Andy McFadden484566c2012-12-18 09:46:54 -0800872 if (bufferProducer != NULL) {
Marco Nelissenee08f7e2013-09-16 13:30:01 -0700873 anw = new Surface(bufferProducer, true /* controlledByApp */);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700874 status_t err = native_window_api_connect(anw.get(),
875 NATIVE_WINDOW_API_MEDIA);
876
877 if (err != OK) {
Steve Block29357bc2012-01-06 19:20:56 +0000878 ALOGE("setVideoSurfaceTexture failed: %d", err);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700879 // Note that we must do the reset before disconnecting from the ANW.
880 // Otherwise queue/dequeue calls could be made on the disconnected
881 // ANW, which may result in errors.
882 reset();
883
884 disconnectNativeWindow();
885
886 return err;
887 }
888 }
889
Andy McFadden484566c2012-12-18 09:46:54 -0800890 // Note that we must set the player's new GraphicBufferProducer before
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700891 // disconnecting the old one. Otherwise queue/dequeue calls could be made
892 // on the disconnected ANW, which may result in errors.
Andy McFadden484566c2012-12-18 09:46:54 -0800893 status_t err = p->setVideoSurfaceTexture(bufferProducer);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700894
895 disconnectNativeWindow();
896
897 mConnectedWindow = anw;
898
899 if (err == OK) {
900 mConnectedWindowBinder = binder;
901 } else {
902 disconnectNativeWindow();
903 }
904
905 return err;
Glenn Kasten11731182011-02-08 17:26:17 -0800906}
907
Nicolas Catania1d187f12009-05-12 23:25:55 -0700908status_t MediaPlayerService::Client::invoke(const Parcel& request,
909 Parcel *reply)
910{
911 sp<MediaPlayerBase> p = getPlayer();
912 if (p == NULL) return UNKNOWN_ERROR;
913 return p->invoke(request, reply);
914}
915
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700916// This call doesn't need to access the native player.
917status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
918{
919 status_t status;
nikoa64c8c72009-07-20 15:07:26 -0700920 media::Metadata::Filter allow, drop;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700921
Nicolas Catania48290382009-07-10 13:53:06 -0700922 if (unmarshallFilter(filter, &allow, &status) &&
923 unmarshallFilter(filter, &drop, &status)) {
924 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700925
926 mMetadataAllow = allow;
927 mMetadataDrop = drop;
928 }
929 return status;
930}
931
Nicolas Catania48290382009-07-10 13:53:06 -0700932status_t MediaPlayerService::Client::getMetadata(
Mark Salyzyn77342f72014-06-18 16:31:32 -0700933 bool update_only, bool /*apply_filter*/, Parcel *reply)
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700934{
nikoa64c8c72009-07-20 15:07:26 -0700935 sp<MediaPlayerBase> player = getPlayer();
936 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania48290382009-07-10 13:53:06 -0700937
nikod608a812009-07-16 16:39:53 -0700938 status_t status;
939 // Placeholder for the return code, updated by the caller.
940 reply->writeInt32(-1);
941
nikoa64c8c72009-07-20 15:07:26 -0700942 media::Metadata::Filter ids;
Nicolas Catania48290382009-07-10 13:53:06 -0700943
944 // We don't block notifications while we fetch the data. We clear
945 // mMetadataUpdated first so we don't lose notifications happening
946 // during the rest of this call.
947 {
948 Mutex::Autolock lock(mLock);
949 if (update_only) {
nikod608a812009-07-16 16:39:53 -0700950 ids = mMetadataUpdated;
Nicolas Catania48290382009-07-10 13:53:06 -0700951 }
952 mMetadataUpdated.clear();
953 }
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700954
nikoa64c8c72009-07-20 15:07:26 -0700955 media::Metadata metadata(reply);
Nicolas Catania48290382009-07-10 13:53:06 -0700956
nikoa64c8c72009-07-20 15:07:26 -0700957 metadata.appendHeader();
958 status = player->getMetadata(ids, reply);
nikod608a812009-07-16 16:39:53 -0700959
960 if (status != OK) {
nikoa64c8c72009-07-20 15:07:26 -0700961 metadata.resetParcel();
Steve Block29357bc2012-01-06 19:20:56 +0000962 ALOGE("getMetadata failed %d", status);
nikod608a812009-07-16 16:39:53 -0700963 return status;
964 }
965
966 // FIXME: Implement filtering on the result. Not critical since
967 // filtering takes place on the update notifications already. This
968 // would be when all the metadata are fetch and a filter is set.
969
nikod608a812009-07-16 16:39:53 -0700970 // Everything is fine, update the metadata length.
nikoa64c8c72009-07-20 15:07:26 -0700971 metadata.updateLength();
nikod608a812009-07-16 16:39:53 -0700972 return OK;
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700973}
974
Wei Jiad399e7e2016-10-26 15:49:11 -0700975status_t MediaPlayerService::Client::setBufferingSettings(
976 const BufferingSettings& buffering)
977{
Wei Jiadc6f3402017-01-09 15:04:18 -0800978 ALOGV("[%d] setBufferingSettings{%s}",
979 mConnId, buffering.toString().string());
Wei Jiad399e7e2016-10-26 15:49:11 -0700980 sp<MediaPlayerBase> p = getPlayer();
981 if (p == 0) return UNKNOWN_ERROR;
982 return p->setBufferingSettings(buffering);
983}
984
985status_t MediaPlayerService::Client::getDefaultBufferingSettings(
986 BufferingSettings* buffering /* nonnull */)
987{
988 sp<MediaPlayerBase> p = getPlayer();
989 // TODO: create mPlayer on demand.
990 if (p == 0) return UNKNOWN_ERROR;
991 status_t ret = p->getDefaultBufferingSettings(buffering);
992 if (ret == NO_ERROR) {
Wei Jiadc6f3402017-01-09 15:04:18 -0800993 ALOGV("[%d] getDefaultBufferingSettings{%s}",
994 mConnId, buffering->toString().string());
Wei Jiad399e7e2016-10-26 15:49:11 -0700995 } else {
996 ALOGV("[%d] getDefaultBufferingSettings returned %d", mConnId, ret);
997 }
998 return ret;
999}
1000
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001001status_t MediaPlayerService::Client::prepareAsync()
1002{
Steve Block3856b092011-10-20 11:56:00 +01001003 ALOGV("[%d] prepareAsync", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001004 sp<MediaPlayerBase> p = getPlayer();
1005 if (p == 0) return UNKNOWN_ERROR;
1006 status_t ret = p->prepareAsync();
1007#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +00001008 ALOGD("start Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001009 if (ret == NO_ERROR) mAntagonizer->start();
1010#endif
1011 return ret;
1012}
1013
1014status_t MediaPlayerService::Client::start()
1015{
Steve Block3856b092011-10-20 11:56:00 +01001016 ALOGV("[%d] start", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001017 sp<MediaPlayerBase> p = getPlayer();
1018 if (p == 0) return UNKNOWN_ERROR;
1019 p->setLooping(mLoop);
1020 return p->start();
1021}
1022
1023status_t MediaPlayerService::Client::stop()
1024{
Steve Block3856b092011-10-20 11:56:00 +01001025 ALOGV("[%d] stop", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001026 sp<MediaPlayerBase> p = getPlayer();
1027 if (p == 0) return UNKNOWN_ERROR;
1028 return p->stop();
1029}
1030
1031status_t MediaPlayerService::Client::pause()
1032{
Steve Block3856b092011-10-20 11:56:00 +01001033 ALOGV("[%d] pause", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001034 sp<MediaPlayerBase> p = getPlayer();
1035 if (p == 0) return UNKNOWN_ERROR;
1036 return p->pause();
1037}
1038
1039status_t MediaPlayerService::Client::isPlaying(bool* state)
1040{
1041 *state = false;
1042 sp<MediaPlayerBase> p = getPlayer();
1043 if (p == 0) return UNKNOWN_ERROR;
1044 *state = p->isPlaying();
Steve Block3856b092011-10-20 11:56:00 +01001045 ALOGV("[%d] isPlaying: %d", mConnId, *state);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001046 return NO_ERROR;
1047}
1048
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001049status_t MediaPlayerService::Client::setPlaybackSettings(const AudioPlaybackRate& rate)
Wei Jia98160162015-02-04 17:01:11 -08001050{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001051 ALOGV("[%d] setPlaybackSettings(%f, %f, %d, %d)",
1052 mConnId, rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Wei Jia98160162015-02-04 17:01:11 -08001053 sp<MediaPlayerBase> p = getPlayer();
1054 if (p == 0) return UNKNOWN_ERROR;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001055 return p->setPlaybackSettings(rate);
1056}
1057
1058status_t MediaPlayerService::Client::getPlaybackSettings(AudioPlaybackRate* rate /* nonnull */)
1059{
1060 sp<MediaPlayerBase> p = getPlayer();
1061 if (p == 0) return UNKNOWN_ERROR;
1062 status_t ret = p->getPlaybackSettings(rate);
1063 if (ret == NO_ERROR) {
1064 ALOGV("[%d] getPlaybackSettings(%f, %f, %d, %d)",
1065 mConnId, rate->mSpeed, rate->mPitch, rate->mFallbackMode, rate->mStretchMode);
1066 } else {
1067 ALOGV("[%d] getPlaybackSettings returned %d", mConnId, ret);
1068 }
1069 return ret;
1070}
1071
1072status_t MediaPlayerService::Client::setSyncSettings(
1073 const AVSyncSettings& sync, float videoFpsHint)
1074{
1075 ALOGV("[%d] setSyncSettings(%u, %u, %f, %f)",
1076 mConnId, sync.mSource, sync.mAudioAdjustMode, sync.mTolerance, videoFpsHint);
1077 sp<MediaPlayerBase> p = getPlayer();
1078 if (p == 0) return UNKNOWN_ERROR;
1079 return p->setSyncSettings(sync, videoFpsHint);
1080}
1081
1082status_t MediaPlayerService::Client::getSyncSettings(
1083 AVSyncSettings* sync /* nonnull */, float* videoFps /* nonnull */)
1084{
1085 sp<MediaPlayerBase> p = getPlayer();
1086 if (p == 0) return UNKNOWN_ERROR;
1087 status_t ret = p->getSyncSettings(sync, videoFps);
1088 if (ret == NO_ERROR) {
1089 ALOGV("[%d] getSyncSettings(%u, %u, %f, %f)",
1090 mConnId, sync->mSource, sync->mAudioAdjustMode, sync->mTolerance, *videoFps);
1091 } else {
1092 ALOGV("[%d] getSyncSettings returned %d", mConnId, ret);
1093 }
1094 return ret;
Wei Jia98160162015-02-04 17:01:11 -08001095}
1096
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001097status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
1098{
Steve Block3856b092011-10-20 11:56:00 +01001099 ALOGV("getCurrentPosition");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001100 sp<MediaPlayerBase> p = getPlayer();
1101 if (p == 0) return UNKNOWN_ERROR;
1102 status_t ret = p->getCurrentPosition(msec);
1103 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001104 ALOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001105 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001106 ALOGE("getCurrentPosition returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001107 }
1108 return ret;
1109}
1110
1111status_t MediaPlayerService::Client::getDuration(int *msec)
1112{
Steve Block3856b092011-10-20 11:56:00 +01001113 ALOGV("getDuration");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001114 sp<MediaPlayerBase> p = getPlayer();
1115 if (p == 0) return UNKNOWN_ERROR;
1116 status_t ret = p->getDuration(msec);
1117 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001118 ALOGV("[%d] getDuration = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001119 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001120 ALOGE("getDuration returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001121 }
1122 return ret;
1123}
1124
Marco Nelissen6b74d672012-02-28 16:07:44 -08001125status_t MediaPlayerService::Client::setNextPlayer(const sp<IMediaPlayer>& player) {
1126 ALOGV("setNextPlayer");
1127 Mutex::Autolock l(mLock);
1128 sp<Client> c = static_cast<Client*>(player.get());
Wei Jia28284122016-08-30 13:49:06 -07001129 if (c != NULL && !mService->hasClient(c)) {
Robert Shihee0a0e32016-08-16 16:50:54 -07001130 return BAD_VALUE;
1131 }
1132
Marco Nelissen6b74d672012-02-28 16:07:44 -08001133 mNextClient = c;
John Grossman5f7e55e2012-08-24 14:47:25 -07001134
1135 if (c != NULL) {
1136 if (mAudioOutput != NULL) {
1137 mAudioOutput->setNextOutput(c->mAudioOutput);
1138 } else if ((mPlayer != NULL) && !mPlayer->hardwareOutput()) {
1139 ALOGE("no current audio output");
1140 }
1141
1142 if ((mPlayer != NULL) && (mNextClient->getPlayer() != NULL)) {
1143 mPlayer->setNextPlayer(mNextClient->getPlayer());
1144 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001145 }
John Grossman5f7e55e2012-08-24 14:47:25 -07001146
Marco Nelissen6b74d672012-02-28 16:07:44 -08001147 return OK;
1148}
1149
Andy Hung9fc8b5c2017-01-24 13:36:48 -08001150VolumeShaper::Status MediaPlayerService::Client::applyVolumeShaper(
1151 const sp<VolumeShaper::Configuration>& configuration,
1152 const sp<VolumeShaper::Operation>& operation) {
1153 // for hardware output, call player instead
1154 ALOGV("Client::applyVolumeShaper(%p)", this);
1155 sp<MediaPlayerBase> p = getPlayer();
1156 {
1157 Mutex::Autolock l(mLock);
1158 if (p != 0 && p->hardwareOutput()) {
1159 // TODO: investigate internal implementation
1160 return VolumeShaper::Status(INVALID_OPERATION);
1161 }
1162 if (mAudioOutput.get() != nullptr) {
1163 return mAudioOutput->applyVolumeShaper(configuration, operation);
1164 }
1165 }
1166 return VolumeShaper::Status(INVALID_OPERATION);
1167}
1168
1169sp<VolumeShaper::State> MediaPlayerService::Client::getVolumeShaperState(int id) {
1170 // for hardware output, call player instead
1171 ALOGV("Client::getVolumeShaperState(%p)", this);
1172 sp<MediaPlayerBase> p = getPlayer();
1173 {
1174 Mutex::Autolock l(mLock);
1175 if (p != 0 && p->hardwareOutput()) {
1176 // TODO: investigate internal implementation.
1177 return nullptr;
1178 }
1179 if (mAudioOutput.get() != nullptr) {
1180 return mAudioOutput->getVolumeShaperState(id);
1181 }
1182 }
1183 return nullptr;
1184}
1185
Wei Jiac5de0912016-11-18 10:22:14 -08001186status_t MediaPlayerService::Client::seekTo(int msec, MediaPlayerSeekMode mode)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001187{
Wei Jiac5de0912016-11-18 10:22:14 -08001188 ALOGV("[%d] seekTo(%d, %d)", mConnId, msec, mode);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001189 sp<MediaPlayerBase> p = getPlayer();
1190 if (p == 0) return UNKNOWN_ERROR;
Wei Jiac5de0912016-11-18 10:22:14 -08001191 return p->seekTo(msec, mode);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001192}
1193
1194status_t MediaPlayerService::Client::reset()
1195{
Steve Block3856b092011-10-20 11:56:00 +01001196 ALOGV("[%d] reset", mConnId);
John Grossmanc795b642012-02-22 15:38:35 -08001197 mRetransmitEndpointValid = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001198 sp<MediaPlayerBase> p = getPlayer();
1199 if (p == 0) return UNKNOWN_ERROR;
1200 return p->reset();
1201}
1202
Glenn Kastenfff6d712012-01-12 16:38:12 -08001203status_t MediaPlayerService::Client::setAudioStreamType(audio_stream_type_t type)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001204{
Steve Block3856b092011-10-20 11:56:00 +01001205 ALOGV("[%d] setAudioStreamType(%d)", mConnId, type);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001206 // TODO: for hardware output, call player instead
1207 Mutex::Autolock l(mLock);
1208 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1209 return NO_ERROR;
1210}
1211
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001212status_t MediaPlayerService::Client::setAudioAttributes_l(const Parcel &parcel)
1213{
1214 if (mAudioAttributes != NULL) { free(mAudioAttributes); }
1215 mAudioAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001216 if (mAudioAttributes == NULL) {
1217 return NO_MEMORY;
1218 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001219 unmarshallAudioAttributes(parcel, mAudioAttributes);
1220
1221 ALOGV("setAudioAttributes_l() usage=%d content=%d flags=0x%x tags=%s",
1222 mAudioAttributes->usage, mAudioAttributes->content_type, mAudioAttributes->flags,
1223 mAudioAttributes->tags);
1224
1225 if (mAudioOutput != 0) {
1226 mAudioOutput->setAudioAttributes(mAudioAttributes);
1227 }
1228 return NO_ERROR;
1229}
1230
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001231status_t MediaPlayerService::Client::setLooping(int loop)
1232{
Steve Block3856b092011-10-20 11:56:00 +01001233 ALOGV("[%d] setLooping(%d)", mConnId, loop);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001234 mLoop = loop;
1235 sp<MediaPlayerBase> p = getPlayer();
1236 if (p != 0) return p->setLooping(loop);
1237 return NO_ERROR;
1238}
1239
1240status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1241{
Steve Block3856b092011-10-20 11:56:00 +01001242 ALOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
John Grossman761defc2012-02-09 15:09:05 -08001243
1244 // for hardware output, call player instead
1245 sp<MediaPlayerBase> p = getPlayer();
1246 {
1247 Mutex::Autolock l(mLock);
1248 if (p != 0 && p->hardwareOutput()) {
1249 MediaPlayerHWInterface* hwp =
1250 reinterpret_cast<MediaPlayerHWInterface*>(p.get());
1251 return hwp->setVolume(leftVolume, rightVolume);
1252 } else {
1253 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1254 return NO_ERROR;
1255 }
1256 }
1257
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001258 return NO_ERROR;
1259}
1260
Eric Laurent2beeb502010-07-16 07:43:46 -07001261status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1262{
Steve Block3856b092011-10-20 11:56:00 +01001263 ALOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
Eric Laurent2beeb502010-07-16 07:43:46 -07001264 Mutex::Autolock l(mLock);
1265 if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1266 return NO_ERROR;
1267}
1268
1269status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1270{
Steve Block3856b092011-10-20 11:56:00 +01001271 ALOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
Eric Laurent2beeb502010-07-16 07:43:46 -07001272 Mutex::Autolock l(mLock);
1273 if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1274 return NO_ERROR;
1275}
Nicolas Catania48290382009-07-10 13:53:06 -07001276
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001277status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
Steve Block3856b092011-10-20 11:56:00 +01001278 ALOGV("[%d] setParameter(%d)", mConnId, key);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001279 switch (key) {
1280 case KEY_PARAMETER_AUDIO_ATTRIBUTES:
1281 {
1282 Mutex::Autolock l(mLock);
1283 return setAudioAttributes_l(request);
1284 }
1285 default:
1286 sp<MediaPlayerBase> p = getPlayer();
1287 if (p == 0) { return UNKNOWN_ERROR; }
1288 return p->setParameter(key, request);
1289 }
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001290}
1291
1292status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
Steve Block3856b092011-10-20 11:56:00 +01001293 ALOGV("[%d] getParameter(%d)", mConnId, key);
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001294 sp<MediaPlayerBase> p = getPlayer();
1295 if (p == 0) return UNKNOWN_ERROR;
1296 return p->getParameter(key, reply);
1297}
1298
John Grossmanc795b642012-02-22 15:38:35 -08001299status_t MediaPlayerService::Client::setRetransmitEndpoint(
1300 const struct sockaddr_in* endpoint) {
1301
1302 if (NULL != endpoint) {
1303 uint32_t a = ntohl(endpoint->sin_addr.s_addr);
1304 uint16_t p = ntohs(endpoint->sin_port);
1305 ALOGV("[%d] setRetransmitEndpoint(%u.%u.%u.%u:%hu)", mConnId,
1306 (a >> 24), (a >> 16) & 0xFF, (a >> 8) & 0xFF, (a & 0xFF), p);
1307 } else {
1308 ALOGV("[%d] setRetransmitEndpoint = <none>", mConnId);
1309 }
1310
1311 sp<MediaPlayerBase> p = getPlayer();
1312
1313 // Right now, the only valid time to set a retransmit endpoint is before
1314 // player selection has been made (since the presence or absence of a
1315 // retransmit endpoint is going to determine which player is selected during
1316 // setDataSource).
1317 if (p != 0) return INVALID_OPERATION;
1318
1319 if (NULL != endpoint) {
1320 mRetransmitEndpoint = *endpoint;
1321 mRetransmitEndpointValid = true;
1322 } else {
1323 mRetransmitEndpointValid = false;
1324 }
1325
1326 return NO_ERROR;
1327}
1328
John Grossman44a7e422012-06-21 17:29:24 -07001329status_t MediaPlayerService::Client::getRetransmitEndpoint(
1330 struct sockaddr_in* endpoint)
1331{
1332 if (NULL == endpoint)
1333 return BAD_VALUE;
1334
1335 sp<MediaPlayerBase> p = getPlayer();
1336
1337 if (p != NULL)
1338 return p->getRetransmitEndpoint(endpoint);
1339
1340 if (!mRetransmitEndpointValid)
1341 return NO_INIT;
1342
1343 *endpoint = mRetransmitEndpoint;
1344
1345 return NO_ERROR;
1346}
1347
Gloria Wangb483c472011-04-11 17:23:27 -07001348void MediaPlayerService::Client::notify(
1349 void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001350{
1351 Client* client = static_cast<Client*>(cookie);
James Dongb8a98252012-08-26 16:13:03 -07001352 if (client == NULL) {
1353 return;
1354 }
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001355
James Dongb8a98252012-08-26 16:13:03 -07001356 sp<IMediaPlayerClient> c;
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001357 sp<Client> nextClient;
1358 status_t errStartNext = NO_ERROR;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001359 {
1360 Mutex::Autolock l(client->mLock);
James Dongb8a98252012-08-26 16:13:03 -07001361 c = client->mClient;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001362 if (msg == MEDIA_PLAYBACK_COMPLETE && client->mNextClient != NULL) {
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001363 nextClient = client->mNextClient;
1364
John Grossmancb0b7552012-08-23 17:47:31 -07001365 if (client->mAudioOutput != NULL)
1366 client->mAudioOutput->switchToNextOutput();
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001367
1368 errStartNext = nextClient->start();
1369 }
1370 }
1371
1372 if (nextClient != NULL) {
1373 sp<IMediaPlayerClient> nc;
1374 {
1375 Mutex::Autolock l(nextClient->mLock);
1376 nc = nextClient->mClient;
1377 }
1378 if (nc != NULL) {
1379 if (errStartNext == NO_ERROR) {
1380 nc->notify(MEDIA_INFO, MEDIA_INFO_STARTED_AS_NEXT, 0, obj);
1381 } else {
1382 nc->notify(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN , 0, obj);
1383 ALOGE("gapless:start playback for next track failed, err(%d)", errStartNext);
Wei Jia2afac0c2016-01-07 12:13:07 -08001384 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001385 }
1386 }
1387
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001388 if (MEDIA_INFO == msg &&
Nicolas Catania48290382009-07-10 13:53:06 -07001389 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikoa64c8c72009-07-20 15:07:26 -07001390 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania48290382009-07-10 13:53:06 -07001391
1392 if(client->shouldDropMetadata(metadata_type)) {
1393 return;
1394 }
1395
1396 // Update the list of metadata that have changed. getMetadata
1397 // also access mMetadataUpdated and clears it.
1398 client->addNewMetadataUpdate(metadata_type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001399 }
James Dongb8a98252012-08-26 16:13:03 -07001400
1401 if (c != NULL) {
1402 ALOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
1403 c->notify(msg, ext1, ext2, obj);
1404 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001405}
1406
Nicolas Catania48290382009-07-10 13:53:06 -07001407
nikoa64c8c72009-07-20 15:07:26 -07001408bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001409{
Nicolas Catania48290382009-07-10 13:53:06 -07001410 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001411
Nicolas Catania48290382009-07-10 13:53:06 -07001412 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001413 return true;
1414 }
1415
Nicolas Catania48290382009-07-10 13:53:06 -07001416 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001417 return false;
Nicolas Catania48290382009-07-10 13:53:06 -07001418 } else {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001419 return true;
1420 }
1421}
1422
Nicolas Catania48290382009-07-10 13:53:06 -07001423
nikoa64c8c72009-07-20 15:07:26 -07001424void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania48290382009-07-10 13:53:06 -07001425 Mutex::Autolock lock(mLock);
1426 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1427 mMetadataUpdated.add(metadata_type);
1428 }
1429}
1430
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001431#if CALLBACK_ANTAGONIZER
1432const int Antagonizer::interval = 10000; // 10 msecs
1433
1434Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1435 mExit(false), mActive(false), mClient(client), mCb(cb)
1436{
1437 createThread(callbackThread, this);
1438}
1439
1440void Antagonizer::kill()
1441{
1442 Mutex::Autolock _l(mLock);
1443 mActive = false;
1444 mExit = true;
1445 mCondition.wait(mLock);
1446}
1447
1448int Antagonizer::callbackThread(void* user)
1449{
Steve Blockb8a80522011-12-20 16:23:08 +00001450 ALOGD("Antagonizer started");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001451 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1452 while (!p->mExit) {
1453 if (p->mActive) {
Steve Block3856b092011-10-20 11:56:00 +01001454 ALOGV("send event");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001455 p->mCb(p->mClient, 0, 0, 0);
1456 }
1457 usleep(interval);
1458 }
1459 Mutex::Autolock _l(p->mLock);
1460 p->mCondition.signal();
Steve Blockb8a80522011-12-20 16:23:08 +00001461 ALOGD("Antagonizer stopped");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001462 return 0;
1463}
1464#endif
1465
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001466#undef LOG_TAG
1467#define LOG_TAG "AudioSink"
Andy Hung1afd0982016-11-08 16:13:44 -08001468MediaPlayerService::AudioOutput::AudioOutput(audio_session_t sessionId, uid_t uid, int pid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001469 const audio_attributes_t* attr)
Andreas Huber20111aa2009-07-14 16:56:47 -07001470 : mCallback(NULL),
Eric Laurenta514bdb2010-06-21 09:27:30 -07001471 mCallbackCookie(NULL),
Marco Nelissen6b74d672012-02-28 16:07:44 -08001472 mCallbackData(NULL),
Andy Hungd1c74342015-07-07 16:54:23 -07001473 mStreamType(AUDIO_STREAM_MUSIC),
Andy Hungd1c74342015-07-07 16:54:23 -07001474 mLeftVolume(1.0),
1475 mRightVolume(1.0),
1476 mPlaybackRate(AUDIO_PLAYBACK_RATE_DEFAULT),
1477 mSampleRateHz(0),
1478 mMsecsPerFrame(0),
1479 mFrameSize(0),
Eric Laurent1948eb32012-04-13 16:50:19 -07001480 mSessionId(sessionId),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001481 mUid(uid),
Marco Nelissend457c972014-02-11 08:47:07 -08001482 mPid(pid),
Andy Hungd1c74342015-07-07 16:54:23 -07001483 mSendLevel(0.0),
1484 mAuxEffectId(0),
1485 mFlags(AUDIO_OUTPUT_FLAG_NONE)
1486{
Steve Block3856b092011-10-20 11:56:00 +01001487 ALOGV("AudioOutput(%d)", sessionId);
Eric Laurent43562692015-07-15 16:49:07 -07001488 if (attr != NULL) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001489 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1490 if (mAttributes != NULL) {
1491 memcpy(mAttributes, attr, sizeof(audio_attributes_t));
1492 mStreamType = audio_attributes_to_stream_type(attr);
1493 }
1494 } else {
1495 mAttributes = NULL;
Eric Laurent43562692015-07-15 16:49:07 -07001496 }
1497
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001498 setMinBufferCount();
1499}
1500
1501MediaPlayerService::AudioOutput::~AudioOutput()
1502{
1503 close();
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001504 free(mAttributes);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001505 delete mCallbackData;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001506}
1507
Andy Hungd1c74342015-07-07 16:54:23 -07001508//static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001509void MediaPlayerService::AudioOutput::setMinBufferCount()
1510{
1511 char value[PROPERTY_VALUE_MAX];
1512 if (property_get("ro.kernel.qemu", value, 0)) {
1513 mIsOnEmulator = true;
1514 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1515 }
1516}
1517
Andy Hungd1c74342015-07-07 16:54:23 -07001518// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001519bool MediaPlayerService::AudioOutput::isOnEmulator()
1520{
Andy Hungd1c74342015-07-07 16:54:23 -07001521 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001522 return mIsOnEmulator;
1523}
1524
Andy Hungd1c74342015-07-07 16:54:23 -07001525// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001526int MediaPlayerService::AudioOutput::getMinBufferCount()
1527{
Andy Hungd1c74342015-07-07 16:54:23 -07001528 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001529 return mMinBufferCount;
1530}
1531
1532ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1533{
Andy Hungd1c74342015-07-07 16:54:23 -07001534 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001535 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001536 return mTrack->frameCount() * mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001537}
1538
1539ssize_t MediaPlayerService::AudioOutput::frameCount() const
1540{
Andy Hungd1c74342015-07-07 16:54:23 -07001541 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001542 if (mTrack == 0) return NO_INIT;
1543 return mTrack->frameCount();
1544}
1545
1546ssize_t MediaPlayerService::AudioOutput::channelCount() const
1547{
Andy Hungd1c74342015-07-07 16:54:23 -07001548 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001549 if (mTrack == 0) return NO_INIT;
1550 return mTrack->channelCount();
1551}
1552
1553ssize_t MediaPlayerService::AudioOutput::frameSize() const
1554{
Andy Hungd1c74342015-07-07 16:54:23 -07001555 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001556 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001557 return mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001558}
1559
1560uint32_t MediaPlayerService::AudioOutput::latency () const
1561{
Andy Hungd1c74342015-07-07 16:54:23 -07001562 Mutex::Autolock lock(mLock);
Eric Laurentdb354e52012-03-05 17:27:11 -08001563 if (mTrack == 0) return 0;
1564 return mTrack->latency();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001565}
1566
1567float MediaPlayerService::AudioOutput::msecsPerFrame() const
1568{
Andy Hungd1c74342015-07-07 16:54:23 -07001569 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001570 return mMsecsPerFrame;
1571}
1572
Marco Nelissen4110c102012-03-29 09:31:28 -07001573status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position) const
Eric Laurent342e9cf2010-01-19 17:37:09 -08001574{
Andy Hungd1c74342015-07-07 16:54:23 -07001575 Mutex::Autolock lock(mLock);
Eric Laurent342e9cf2010-01-19 17:37:09 -08001576 if (mTrack == 0) return NO_INIT;
1577 return mTrack->getPosition(position);
1578}
1579
Lajos Molnar06ad1522014-08-28 07:27:44 -07001580status_t MediaPlayerService::AudioOutput::getTimestamp(AudioTimestamp &ts) const
1581{
Andy Hungd1c74342015-07-07 16:54:23 -07001582 Mutex::Autolock lock(mLock);
Lajos Molnar06ad1522014-08-28 07:27:44 -07001583 if (mTrack == 0) return NO_INIT;
1584 return mTrack->getTimestamp(ts);
1585}
1586
Wei Jiac4ac8172015-10-21 10:35:48 -07001587// TODO: Remove unnecessary calls to getPlayedOutDurationUs()
1588// as it acquires locks and may query the audio driver.
1589//
1590// Some calls could conceivably retrieve extrapolated data instead of
1591// accessing getTimestamp() or getPosition() every time a data buffer with
1592// a media time is received.
1593//
1594// Calculate duration of played samples if played at normal rate (i.e., 1.0).
1595int64_t MediaPlayerService::AudioOutput::getPlayedOutDurationUs(int64_t nowUs) const
1596{
1597 Mutex::Autolock lock(mLock);
1598 if (mTrack == 0 || mSampleRateHz == 0) {
Wei Jia213f4902015-10-22 08:55:25 -07001599 return 0;
Wei Jiac4ac8172015-10-21 10:35:48 -07001600 }
1601
1602 uint32_t numFramesPlayed;
Andy Hung5d313802016-10-10 15:09:39 -07001603 int64_t numFramesPlayedAtUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001604 AudioTimestamp ts;
Wei Jiac4ac8172015-10-21 10:35:48 -07001605
1606 status_t res = mTrack->getTimestamp(ts);
1607 if (res == OK) { // case 1: mixing audio tracks and offloaded tracks.
1608 numFramesPlayed = ts.mPosition;
Andy Hung5d313802016-10-10 15:09:39 -07001609 numFramesPlayedAtUs = ts.mTime.tv_sec * 1000000LL + ts.mTime.tv_nsec / 1000;
1610 //ALOGD("getTimestamp: OK %d %lld", numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001611 } else if (res == WOULD_BLOCK) { // case 2: transitory state on start of a new track
1612 numFramesPlayed = 0;
Andy Hung5d313802016-10-10 15:09:39 -07001613 numFramesPlayedAtUs = nowUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001614 //ALOGD("getTimestamp: WOULD_BLOCK %d %lld",
Andy Hung5d313802016-10-10 15:09:39 -07001615 // numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001616 } else { // case 3: transitory at new track or audio fast tracks.
1617 res = mTrack->getPosition(&numFramesPlayed);
1618 CHECK_EQ(res, (status_t)OK);
Andy Hung5d313802016-10-10 15:09:39 -07001619 numFramesPlayedAtUs = nowUs;
1620 numFramesPlayedAtUs += 1000LL * mTrack->latency() / 2; /* XXX */
1621 //ALOGD("getPosition: %u %lld", numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001622 }
1623
1624 // CHECK_EQ(numFramesPlayed & (1 << 31), 0); // can't be negative until 12.4 hrs, test
1625 // TODO: remove the (int32_t) casting below as it may overflow at 12.4 hours.
1626 int64_t durationUs = (int64_t)((int32_t)numFramesPlayed * 1000000LL / mSampleRateHz)
Andy Hung5d313802016-10-10 15:09:39 -07001627 + nowUs - numFramesPlayedAtUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001628 if (durationUs < 0) {
1629 // Occurs when numFramesPlayed position is very small and the following:
1630 // (1) In case 1, the time nowUs is computed before getTimestamp() is called and
Andy Hung5d313802016-10-10 15:09:39 -07001631 // numFramesPlayedAtUs is greater than nowUs by time more than numFramesPlayed.
Wei Jiac4ac8172015-10-21 10:35:48 -07001632 // (2) In case 3, using getPosition and adding mAudioSink->latency() to
Andy Hung5d313802016-10-10 15:09:39 -07001633 // numFramesPlayedAtUs, by a time amount greater than numFramesPlayed.
Wei Jiac4ac8172015-10-21 10:35:48 -07001634 //
1635 // Both of these are transitory conditions.
1636 ALOGV("getPlayedOutDurationUs: negative duration %lld set to zero", (long long)durationUs);
1637 durationUs = 0;
1638 }
1639 ALOGV("getPlayedOutDurationUs(%lld) nowUs(%lld) frames(%u) framesAt(%lld)",
Andy Hung5d313802016-10-10 15:09:39 -07001640 (long long)durationUs, (long long)nowUs,
1641 numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001642 return durationUs;
1643}
1644
Marco Nelissen4110c102012-03-29 09:31:28 -07001645status_t MediaPlayerService::AudioOutput::getFramesWritten(uint32_t *frameswritten) const
1646{
Andy Hungd1c74342015-07-07 16:54:23 -07001647 Mutex::Autolock lock(mLock);
Marco Nelissen4110c102012-03-29 09:31:28 -07001648 if (mTrack == 0) return NO_INIT;
Andy Hung2f6e73d2016-04-08 12:12:58 -07001649 ExtendedTimestamp ets;
1650 status_t status = mTrack->getTimestamp(&ets);
1651 if (status == OK || status == WOULD_BLOCK) {
1652 *frameswritten = (uint32_t)ets.mPosition[ExtendedTimestamp::LOCATION_CLIENT];
1653 }
1654 return status;
Marco Nelissen4110c102012-03-29 09:31:28 -07001655}
1656
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001657status_t MediaPlayerService::AudioOutput::setParameters(const String8& keyValuePairs)
1658{
Andy Hungd1c74342015-07-07 16:54:23 -07001659 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001660 if (mTrack == 0) return NO_INIT;
1661 return mTrack->setParameters(keyValuePairs);
1662}
1663
1664String8 MediaPlayerService::AudioOutput::getParameters(const String8& keys)
1665{
Andy Hungd1c74342015-07-07 16:54:23 -07001666 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001667 if (mTrack == 0) return String8::empty();
1668 return mTrack->getParameters(keys);
1669}
1670
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001671void MediaPlayerService::AudioOutput::setAudioAttributes(const audio_attributes_t * attributes) {
Andy Hungd1c74342015-07-07 16:54:23 -07001672 Mutex::Autolock lock(mLock);
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001673 if (attributes == NULL) {
1674 free(mAttributes);
1675 mAttributes = NULL;
1676 } else {
1677 if (mAttributes == NULL) {
1678 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1679 }
1680 memcpy(mAttributes, attributes, sizeof(audio_attributes_t));
Eric Laurent43562692015-07-15 16:49:07 -07001681 mStreamType = audio_attributes_to_stream_type(attributes);
1682 }
1683}
1684
1685void MediaPlayerService::AudioOutput::setAudioStreamType(audio_stream_type_t streamType)
1686{
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001687 Mutex::Autolock lock(mLock);
Eric Laurent43562692015-07-15 16:49:07 -07001688 // do not allow direct stream type modification if attributes have been set
1689 if (mAttributes == NULL) {
1690 mStreamType = streamType;
1691 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001692}
1693
Andy Hungd1c74342015-07-07 16:54:23 -07001694void MediaPlayerService::AudioOutput::deleteRecycledTrack_l()
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001695{
Andy Hungd1c74342015-07-07 16:54:23 -07001696 ALOGV("deleteRecycledTrack_l");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001697 if (mRecycledTrack != 0) {
1698
1699 if (mCallbackData != NULL) {
1700 mCallbackData->setOutput(NULL);
1701 mCallbackData->endTrackSwitch();
1702 }
1703
1704 if ((mRecycledTrack->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) {
Andy Hunge13f8a62016-03-30 14:20:42 -07001705 int32_t msec = 0;
1706 if (!mRecycledTrack->stopped()) { // check if active
1707 (void)mRecycledTrack->pendingDuration(&msec);
1708 }
1709 mRecycledTrack->stop(); // ensure full data drain
1710 ALOGD("deleting recycled track, waiting for data drain (%d msec)", msec);
1711 if (msec > 0) {
1712 static const int32_t WAIT_LIMIT_MS = 3000;
1713 if (msec > WAIT_LIMIT_MS) {
1714 msec = WAIT_LIMIT_MS;
1715 }
1716 usleep(msec * 1000LL);
1717 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001718 }
1719 // An offloaded track isn't flushed because the STREAM_END is reported
1720 // slightly prematurely to allow time for the gapless track switch
1721 // but this means that if we decide not to recycle the track there
1722 // could be a small amount of residual data still playing. We leave
1723 // AudioFlinger to drain the track.
1724
1725 mRecycledTrack.clear();
Andy Hungd1c74342015-07-07 16:54:23 -07001726 close_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001727 delete mCallbackData;
1728 mCallbackData = NULL;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001729 }
1730}
1731
Andy Hungd1c74342015-07-07 16:54:23 -07001732void MediaPlayerService::AudioOutput::close_l()
1733{
1734 mTrack.clear();
1735}
1736
Andreas Huber20111aa2009-07-14 16:56:47 -07001737status_t MediaPlayerService::AudioOutput::open(
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001738 uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
1739 audio_format_t format, int bufferCount,
Eric Laurent1948eb32012-04-13 16:50:19 -07001740 AudioCallback cb, void *cookie,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001741 audio_output_flags_t flags,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001742 const audio_offload_info_t *offloadInfo,
Andy Hung179652e2015-05-31 22:49:46 -07001743 bool doNotReconnect,
1744 uint32_t suggestedFrameCount)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001745{
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001746 ALOGV("open(%u, %d, 0x%x, 0x%x, %d, %d 0x%x)", sampleRate, channelCount, channelMask,
1747 format, bufferCount, mSessionId, flags);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001748
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001749 // offloading is only supported in callback mode for now.
1750 // offloadInfo must be present if offload flag is set
1751 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) &&
1752 ((cb == NULL) || (offloadInfo == NULL))) {
1753 return BAD_VALUE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001754 }
1755
Andy Hung179652e2015-05-31 22:49:46 -07001756 // compute frame count for the AudioTrack internal buffer
1757 size_t frameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001758 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1759 frameCount = 0; // AudioTrack will get frame count from AudioFlinger
1760 } else {
Andy Hung179652e2015-05-31 22:49:46 -07001761 // try to estimate the buffer processing fetch size from AudioFlinger.
1762 // framesPerBuffer is approximate and generally correct, except when it's not :-).
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001763 uint32_t afSampleRate;
1764 size_t afFrameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001765 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1766 return NO_INIT;
1767 }
1768 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1769 return NO_INIT;
1770 }
Andy Hung179652e2015-05-31 22:49:46 -07001771 const size_t framesPerBuffer =
1772 (unsigned long long)sampleRate * afFrameCount / afSampleRate;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001773
Andy Hung179652e2015-05-31 22:49:46 -07001774 if (bufferCount == 0) {
1775 // use suggestedFrameCount
1776 bufferCount = (suggestedFrameCount + framesPerBuffer - 1) / framesPerBuffer;
1777 }
1778 // Check argument bufferCount against the mininum buffer count
1779 if (bufferCount != 0 && bufferCount < mMinBufferCount) {
1780 ALOGV("bufferCount (%d) increased to %d", bufferCount, mMinBufferCount);
1781 bufferCount = mMinBufferCount;
1782 }
1783 // if frameCount is 0, then AudioTrack will get frame count from AudioFlinger
1784 // which will be the minimum size permitted.
1785 frameCount = bufferCount * framesPerBuffer;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001786 }
Andreas Huber20111aa2009-07-14 16:56:47 -07001787
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001788 if (channelMask == CHANNEL_MASK_USE_CHANNEL_ORDER) {
Glenn Kastenab334fd2012-03-14 12:56:06 -07001789 channelMask = audio_channel_out_mask_from_count(channelCount);
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001790 if (0 == channelMask) {
1791 ALOGE("open() error, can\'t derive mask for %d audio channels", channelCount);
1792 return NO_INIT;
1793 }
1794 }
Eric Laurent1948eb32012-04-13 16:50:19 -07001795
Andy Hungd1c74342015-07-07 16:54:23 -07001796 Mutex::Autolock lock(mLock);
Andy Hung179652e2015-05-31 22:49:46 -07001797 mCallback = cb;
1798 mCallbackCookie = cookie;
1799
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001800 // Check whether we can recycle the track
1801 bool reuse = false;
1802 bool bothOffloaded = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001803
Glenn Kasten2799d742013-05-30 14:33:29 -07001804 if (mRecycledTrack != 0) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001805 // check whether we are switching between two offloaded tracks
1806 bothOffloaded = (flags & mRecycledTrack->getFlags()
1807 & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0;
Marco Nelissen67295b52012-06-11 14:52:53 -07001808
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001809 // check if the existing track can be reused as-is, or if a new track needs to be created.
1810 reuse = true;
1811
Marco Nelissen67295b52012-06-11 14:52:53 -07001812 if ((mCallbackData == NULL && mCallback != NULL) ||
1813 (mCallbackData != NULL && mCallback == NULL)) {
1814 // recycled track uses callbacks but the caller wants to use writes, or vice versa
1815 ALOGV("can't chain callback and write");
1816 reuse = false;
1817 } else if ((mRecycledTrack->getSampleRate() != sampleRate) ||
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001818 (mRecycledTrack->channelCount() != (uint32_t)channelCount) ) {
1819 ALOGV("samplerate, channelcount differ: %u/%u Hz, %u/%d ch",
Marco Nelissen67295b52012-06-11 14:52:53 -07001820 mRecycledTrack->getSampleRate(), sampleRate,
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001821 mRecycledTrack->channelCount(), channelCount);
Marco Nelissen67295b52012-06-11 14:52:53 -07001822 reuse = false;
1823 } else if (flags != mFlags) {
1824 ALOGV("output flags differ %08x/%08x", flags, mFlags);
1825 reuse = false;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001826 } else if (mRecycledTrack->format() != format) {
1827 reuse = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001828 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001829 } else {
1830 ALOGV("no track available to recycle");
1831 }
1832
1833 ALOGV_IF(bothOffloaded, "both tracks offloaded");
1834
1835 // If we can't recycle and both tracks are offloaded
1836 // we must close the previous output before opening a new one
1837 if (bothOffloaded && !reuse) {
1838 ALOGV("both offloaded and not recycling");
Andy Hungd1c74342015-07-07 16:54:23 -07001839 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001840 }
1841
1842 sp<AudioTrack> t;
1843 CallbackData *newcbd = NULL;
1844
1845 // We don't attempt to create a new track if we are recycling an
1846 // offloaded track. But, if we are recycling a non-offloaded or we
1847 // are switching where one is offloaded and one isn't then we create
1848 // the new track in advance so that we can read additional stream info
1849
1850 if (!(reuse && bothOffloaded)) {
1851 ALOGV("creating new AudioTrack");
1852
1853 if (mCallback != NULL) {
1854 newcbd = new CallbackData(this);
1855 t = new AudioTrack(
1856 mStreamType,
1857 sampleRate,
1858 format,
1859 channelMask,
1860 frameCount,
1861 flags,
1862 CallbackWrapper,
1863 newcbd,
1864 0, // notification frames
1865 mSessionId,
1866 AudioTrack::TRANSFER_CALLBACK,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001867 offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -08001868 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001869 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001870 mAttributes,
1871 doNotReconnect);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001872 } else {
Andy Hungff874dc2016-04-11 16:49:09 -07001873 // TODO: Due to buffer memory concerns, we use a max target playback speed
1874 // based on mPlaybackRate at the time of open (instead of kMaxRequiredSpeed),
1875 // also clamping the target speed to 1.0 <= targetSpeed <= kMaxRequiredSpeed.
1876 const float targetSpeed =
1877 std::min(std::max(mPlaybackRate.mSpeed, 1.0f), kMaxRequiredSpeed);
1878 ALOGW_IF(targetSpeed != mPlaybackRate.mSpeed,
1879 "track target speed:%f clamped from playback speed:%f",
1880 targetSpeed, mPlaybackRate.mSpeed);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001881 t = new AudioTrack(
1882 mStreamType,
1883 sampleRate,
1884 format,
1885 channelMask,
1886 frameCount,
1887 flags,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001888 NULL, // callback
1889 NULL, // user data
1890 0, // notification frames
1891 mSessionId,
1892 AudioTrack::TRANSFER_DEFAULT,
1893 NULL, // offload info
Marco Nelissend457c972014-02-11 08:47:07 -08001894 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001895 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001896 mAttributes,
Andy Hungff874dc2016-04-11 16:49:09 -07001897 doNotReconnect,
1898 targetSpeed);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001899 }
1900
1901 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1902 ALOGE("Unable to create audio track");
1903 delete newcbd;
Glenn Kasten3e98ecd2015-05-18 13:13:24 -07001904 // t goes out of scope, so reference count drops to zero
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001905 return NO_INIT;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001906 } else {
1907 // successful AudioTrack initialization implies a legacy stream type was generated
1908 // from the audio attributes
1909 mStreamType = t->streamType();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001910 }
1911 }
1912
1913 if (reuse) {
1914 CHECK(mRecycledTrack != NULL);
1915
1916 if (!bothOffloaded) {
1917 if (mRecycledTrack->frameCount() != t->frameCount()) {
Andy Hung833b4752016-04-04 17:15:48 -07001918 ALOGV("framecount differs: %zu/%zu frames",
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001919 mRecycledTrack->frameCount(), t->frameCount());
1920 reuse = false;
1921 }
1922 }
1923
Marco Nelissen67295b52012-06-11 14:52:53 -07001924 if (reuse) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001925 ALOGV("chaining to next output and recycling track");
Andy Hungd1c74342015-07-07 16:54:23 -07001926 close_l();
Marco Nelissen67295b52012-06-11 14:52:53 -07001927 mTrack = mRecycledTrack;
Glenn Kasten2799d742013-05-30 14:33:29 -07001928 mRecycledTrack.clear();
Marco Nelissen67295b52012-06-11 14:52:53 -07001929 if (mCallbackData != NULL) {
1930 mCallbackData->setOutput(this);
1931 }
Marco Nelissen67295b52012-06-11 14:52:53 -07001932 delete newcbd;
Wei Jiae0bbac92016-07-18 16:04:53 -07001933 return updateTrack();
Marco Nelissen67295b52012-06-11 14:52:53 -07001934 }
Marco Nelissen67295b52012-06-11 14:52:53 -07001935 }
1936
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001937 // we're not going to reuse the track, unblock and flush it
1938 // this was done earlier if both tracks are offloaded
1939 if (!bothOffloaded) {
Andy Hungd1c74342015-07-07 16:54:23 -07001940 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001941 }
1942
1943 CHECK((t != NULL) && ((mCallback == NULL) || (newcbd != NULL)));
1944
Marco Nelissen67295b52012-06-11 14:52:53 -07001945 mCallbackData = newcbd;
Steve Block3856b092011-10-20 11:56:00 +01001946 ALOGV("setVolume");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001947 t->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07001948
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001949 mSampleRateHz = sampleRate;
Preetam Singh Ranawat2e17eef2015-08-12 12:11:46 -07001950 mFlags = flags;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001951 mMsecsPerFrame = 1E3f / (mPlaybackRate.mSpeed * sampleRate);
Andy Hungd1c74342015-07-07 16:54:23 -07001952 mFrameSize = t->frameSize();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001953 mTrack = t;
Eric Laurent2beeb502010-07-16 07:43:46 -07001954
Wei Jiae0bbac92016-07-18 16:04:53 -07001955 return updateTrack();
1956}
1957
1958status_t MediaPlayerService::AudioOutput::updateTrack() {
1959 if (mTrack == NULL) {
1960 return NO_ERROR;
1961 }
1962
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001963 status_t res = NO_ERROR;
Wei Jia0162d002015-06-09 11:59:33 -07001964 // Note some output devices may give us a direct track even though we don't specify it.
1965 // Example: Line application b/17459982.
Wei Jiae0bbac92016-07-18 16:04:53 -07001966 if ((mTrack->getFlags()
1967 & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) {
1968 res = mTrack->setPlaybackRate(mPlaybackRate);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001969 if (res == NO_ERROR) {
Wei Jiae0bbac92016-07-18 16:04:53 -07001970 mTrack->setAuxEffectSendLevel(mSendLevel);
1971 res = mTrack->attachAuxEffect(mAuxEffectId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001972 }
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001973 }
Wei Jiae0bbac92016-07-18 16:04:53 -07001974 ALOGV("updateTrack() DONE status %d", res);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001975 return res;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001976}
1977
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001978status_t MediaPlayerService::AudioOutput::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001979{
Steve Block3856b092011-10-20 11:56:00 +01001980 ALOGV("start");
Andy Hungd1c74342015-07-07 16:54:23 -07001981 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001982 if (mCallbackData != NULL) {
1983 mCallbackData->endTrackSwitch();
1984 }
Glenn Kasten2799d742013-05-30 14:33:29 -07001985 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001986 mTrack->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07001987 mTrack->setAuxEffectSendLevel(mSendLevel);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001988 return mTrack->start();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001989 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001990 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001991}
1992
Marco Nelissen6b74d672012-02-28 16:07:44 -08001993void MediaPlayerService::AudioOutput::setNextOutput(const sp<AudioOutput>& nextOutput) {
Andy Hungd1c74342015-07-07 16:54:23 -07001994 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001995 mNextOutput = nextOutput;
1996}
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08001997
Marco Nelissen6b74d672012-02-28 16:07:44 -08001998void MediaPlayerService::AudioOutput::switchToNextOutput() {
1999 ALOGV("switchToNextOutput");
Andy Hungd1c74342015-07-07 16:54:23 -07002000
2001 // Try to acquire the callback lock before moving track (without incurring deadlock).
2002 const unsigned kMaxSwitchTries = 100;
2003 Mutex::Autolock lock(mLock);
2004 for (unsigned tries = 0;;) {
2005 if (mTrack == 0) {
2006 return;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002007 }
Andy Hungd1c74342015-07-07 16:54:23 -07002008 if (mNextOutput != NULL && mNextOutput != this) {
2009 if (mCallbackData != NULL) {
2010 // two alternative approaches
2011#if 1
2012 CallbackData *callbackData = mCallbackData;
2013 mLock.unlock();
2014 // proper acquisition sequence
2015 callbackData->lock();
2016 mLock.lock();
2017 // Caution: it is unlikely that someone deleted our callback or changed our target
2018 if (callbackData != mCallbackData || mNextOutput == NULL || mNextOutput == this) {
2019 // fatal if we are starved out.
2020 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
2021 "switchToNextOutput() cannot obtain correct lock sequence");
2022 callbackData->unlock();
2023 continue;
2024 }
2025 callbackData->mSwitching = true; // begin track switch
Wei Jiaadee56a2016-08-05 15:40:34 -07002026 callbackData->setOutput(NULL);
Andy Hungd1c74342015-07-07 16:54:23 -07002027#else
2028 // tryBeginTrackSwitch() returns false if the callback has the lock.
2029 if (!mCallbackData->tryBeginTrackSwitch()) {
2030 // fatal if we are starved out.
2031 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
2032 "switchToNextOutput() cannot obtain callback lock");
2033 mLock.unlock();
2034 usleep(5 * 1000 /* usec */); // allow callback to use AudioOutput
2035 mLock.lock();
2036 continue;
2037 }
2038#endif
2039 }
2040
2041 Mutex::Autolock nextLock(mNextOutput->mLock);
2042
2043 // If the next output track is not NULL, then it has been
2044 // opened already for playback.
2045 // This is possible even without the next player being started,
2046 // for example, the next player could be prepared and seeked.
2047 //
2048 // Presuming it isn't advisable to force the track over.
2049 if (mNextOutput->mTrack == NULL) {
2050 ALOGD("Recycling track for gapless playback");
2051 delete mNextOutput->mCallbackData;
2052 mNextOutput->mCallbackData = mCallbackData;
2053 mNextOutput->mRecycledTrack = mTrack;
2054 mNextOutput->mSampleRateHz = mSampleRateHz;
2055 mNextOutput->mMsecsPerFrame = mMsecsPerFrame;
Andy Hungd1c74342015-07-07 16:54:23 -07002056 mNextOutput->mFlags = mFlags;
2057 mNextOutput->mFrameSize = mFrameSize;
2058 close_l();
2059 mCallbackData = NULL; // destruction handled by mNextOutput
2060 } else {
2061 ALOGW("Ignoring gapless playback because next player has already started");
2062 // remove track in case resource needed for future players.
2063 if (mCallbackData != NULL) {
2064 mCallbackData->endTrackSwitch(); // release lock for callbacks before close.
2065 }
2066 close_l();
2067 }
2068 }
2069 break;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002070 }
2071}
2072
Wei Jia7d3f4df2015-03-03 15:28:00 -08002073ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002074{
Andy Hungd1c74342015-07-07 16:54:23 -07002075 Mutex::Autolock lock(mLock);
Glenn Kastenadad3d72014-02-21 14:51:43 -08002076 LOG_ALWAYS_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
Andreas Huber20111aa2009-07-14 16:56:47 -07002077
Steve Block3856b092011-10-20 11:56:00 +01002078 //ALOGV("write(%p, %u)", buffer, size);
Glenn Kasten2799d742013-05-30 14:33:29 -07002079 if (mTrack != 0) {
Andy Hung2f6e73d2016-04-08 12:12:58 -07002080 return mTrack->write(buffer, size, blocking);
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07002081 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002082 return NO_INIT;
2083}
2084
2085void MediaPlayerService::AudioOutput::stop()
2086{
Steve Block3856b092011-10-20 11:56:00 +01002087 ALOGV("stop");
Andy Hungd1c74342015-07-07 16:54:23 -07002088 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002089 if (mTrack != 0) mTrack->stop();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002090}
2091
2092void MediaPlayerService::AudioOutput::flush()
2093{
Steve Block3856b092011-10-20 11:56:00 +01002094 ALOGV("flush");
Andy Hungd1c74342015-07-07 16:54:23 -07002095 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002096 if (mTrack != 0) mTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002097}
2098
2099void MediaPlayerService::AudioOutput::pause()
2100{
Steve Block3856b092011-10-20 11:56:00 +01002101 ALOGV("pause");
Andy Hungd1c74342015-07-07 16:54:23 -07002102 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002103 if (mTrack != 0) mTrack->pause();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002104}
2105
2106void MediaPlayerService::AudioOutput::close()
2107{
Steve Block3856b092011-10-20 11:56:00 +01002108 ALOGV("close");
Erik Wolsheimer7845a1f2015-10-30 12:07:52 -07002109 sp<AudioTrack> track;
2110 {
2111 Mutex::Autolock lock(mLock);
2112 track = mTrack;
2113 close_l(); // clears mTrack
2114 }
2115 // destruction of the track occurs outside of mutex.
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002116}
2117
2118void MediaPlayerService::AudioOutput::setVolume(float left, float right)
2119{
Steve Block3856b092011-10-20 11:56:00 +01002120 ALOGV("setVolume(%f, %f)", left, right);
Andy Hungd1c74342015-07-07 16:54:23 -07002121 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002122 mLeftVolume = left;
2123 mRightVolume = right;
Glenn Kasten2799d742013-05-30 14:33:29 -07002124 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002125 mTrack->setVolume(left, right);
2126 }
2127}
2128
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002129status_t MediaPlayerService::AudioOutput::setPlaybackRate(const AudioPlaybackRate &rate)
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002130{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002131 ALOGV("setPlaybackRate(%f %f %d %d)",
2132 rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Andy Hungd1c74342015-07-07 16:54:23 -07002133 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002134 if (mTrack == 0) {
2135 // remember rate so that we can set it when the track is opened
2136 mPlaybackRate = rate;
2137 return OK;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002138 }
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002139 status_t res = mTrack->setPlaybackRate(rate);
2140 if (res != NO_ERROR) {
2141 return res;
2142 }
2143 // rate.mSpeed is always greater than 0 if setPlaybackRate succeeded
2144 CHECK_GT(rate.mSpeed, 0.f);
2145 mPlaybackRate = rate;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002146 if (mSampleRateHz != 0) {
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002147 mMsecsPerFrame = 1E3f / (rate.mSpeed * mSampleRateHz);
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002148 }
2149 return res;
2150}
2151
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002152status_t MediaPlayerService::AudioOutput::getPlaybackRate(AudioPlaybackRate *rate)
2153{
2154 ALOGV("setPlaybackRate");
Andy Hungd1c74342015-07-07 16:54:23 -07002155 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002156 if (mTrack == 0) {
2157 return NO_INIT;
2158 }
2159 *rate = mTrack->getPlaybackRate();
2160 return NO_ERROR;
2161}
2162
Eric Laurent2beeb502010-07-16 07:43:46 -07002163status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
2164{
Steve Block3856b092011-10-20 11:56:00 +01002165 ALOGV("setAuxEffectSendLevel(%f)", level);
Andy Hungd1c74342015-07-07 16:54:23 -07002166 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002167 mSendLevel = level;
Glenn Kasten2799d742013-05-30 14:33:29 -07002168 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002169 return mTrack->setAuxEffectSendLevel(level);
2170 }
2171 return NO_ERROR;
2172}
2173
2174status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
2175{
Steve Block3856b092011-10-20 11:56:00 +01002176 ALOGV("attachAuxEffect(%d)", effectId);
Andy Hungd1c74342015-07-07 16:54:23 -07002177 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002178 mAuxEffectId = effectId;
Glenn Kasten2799d742013-05-30 14:33:29 -07002179 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002180 return mTrack->attachAuxEffect(effectId);
2181 }
2182 return NO_ERROR;
2183}
2184
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002185VolumeShaper::Status MediaPlayerService::AudioOutput::applyVolumeShaper(
2186 const sp<VolumeShaper::Configuration>& configuration,
2187 const sp<VolumeShaper::Operation>& operation)
2188{
2189 Mutex::Autolock lock(mLock);
2190 ALOGV("AudioOutput::applyVolumeShaper");
2191 if (mTrack != 0) {
2192 return mTrack->applyVolumeShaper(configuration, operation);
2193 }
2194 return VolumeShaper::Status(INVALID_OPERATION);
2195}
2196
2197sp<VolumeShaper::State> MediaPlayerService::AudioOutput::getVolumeShaperState(int id)
2198{
2199 Mutex::Autolock lock(mLock);
2200 if (mTrack != 0) {
2201 return mTrack->getVolumeShaperState(id);
2202 }
2203 return nullptr;
2204}
2205
Andreas Huber20111aa2009-07-14 16:56:47 -07002206// static
2207void MediaPlayerService::AudioOutput::CallbackWrapper(
Glenn Kastend217a8c2011-06-01 15:20:35 -07002208 int event, void *cookie, void *info) {
Steve Block3856b092011-10-20 11:56:00 +01002209 //ALOGV("callbackwrapper");
Marco Nelissen6b74d672012-02-28 16:07:44 -08002210 CallbackData *data = (CallbackData*)cookie;
Andy Hungd1c74342015-07-07 16:54:23 -07002211 // lock to ensure we aren't caught in the middle of a track switch.
Marco Nelissen6b74d672012-02-28 16:07:44 -08002212 data->lock();
2213 AudioOutput *me = data->getOutput();
Andreas Huber20111aa2009-07-14 16:56:47 -07002214 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002215 if (me == NULL) {
2216 // no output set, likely because the track was scheduled to be reused
2217 // by another player, but the format turned out to be incompatible.
2218 data->unlock();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002219 if (buffer != NULL) {
2220 buffer->size = 0;
2221 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08002222 return;
2223 }
Andreas Huber20111aa2009-07-14 16:56:47 -07002224
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002225 switch(event) {
2226 case AudioTrack::EVENT_MORE_DATA: {
2227 size_t actualSize = (*me->mCallback)(
2228 me, buffer->raw, buffer->size, me->mCallbackCookie,
2229 CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002230
Andy Hung719b46b2015-05-31 22:18:25 -07002231 // Log when no data is returned from the callback.
2232 // (1) We may have no data (especially with network streaming sources).
2233 // (2) We may have reached the EOS and the audio track is not stopped yet.
2234 // Note that AwesomePlayer/AudioPlayer will only return zero size when it reaches the EOS.
2235 // NuPlayerRenderer will return zero when it doesn't have data (it doesn't block to fill).
2236 //
2237 // This is a benign busy-wait, with the next data request generated 10 ms or more later;
2238 // nevertheless for power reasons, we don't want to see too many of these.
Andreas Huber2e8ffaf2010-02-18 16:45:13 -08002239
Andy Hung719b46b2015-05-31 22:18:25 -07002240 ALOGV_IF(actualSize == 0 && buffer->size > 0, "callbackwrapper: empty buffer returned");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002241
2242 buffer->size = actualSize;
2243 } break;
2244
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002245 case AudioTrack::EVENT_STREAM_END:
Andy Hung719b46b2015-05-31 22:18:25 -07002246 // currently only occurs for offloaded callbacks
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002247 ALOGV("callbackwrapper: deliver EVENT_STREAM_END");
2248 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2249 me->mCallbackCookie, CB_EVENT_STREAM_END);
2250 break;
2251
2252 case AudioTrack::EVENT_NEW_IAUDIOTRACK :
2253 ALOGV("callbackwrapper: deliver EVENT_TEAR_DOWN");
2254 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2255 me->mCallbackCookie, CB_EVENT_TEAR_DOWN);
2256 break;
2257
Glenn Kasten421743b2015-06-01 08:18:08 -07002258 case AudioTrack::EVENT_UNDERRUN:
Andy Hung719b46b2015-05-31 22:18:25 -07002259 // This occurs when there is no data available, typically
Glenn Kasten421743b2015-06-01 08:18:08 -07002260 // when there is a failure to supply data to the AudioTrack. It can also
2261 // occur in non-offloaded mode when the audio device comes out of standby.
2262 //
Andy Hung719b46b2015-05-31 22:18:25 -07002263 // If an AudioTrack underruns it outputs silence. Since this happens suddenly
2264 // it may sound like an audible pop or glitch.
2265 //
2266 // The underrun event is sent once per track underrun; the condition is reset
2267 // when more data is sent to the AudioTrack.
Eric Laurente93cc032016-05-05 10:15:10 -07002268 ALOGD("callbackwrapper: EVENT_UNDERRUN (discarded)");
Glenn Kasten421743b2015-06-01 08:18:08 -07002269 break;
2270
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002271 default:
2272 ALOGE("received unknown event type: %d inside CallbackWrapper !", event);
Andreas Huber51c1e0e2011-04-04 11:43:40 -07002273 }
2274
Marco Nelissen6b74d672012-02-28 16:07:44 -08002275 data->unlock();
Andreas Huber20111aa2009-07-14 16:56:47 -07002276}
2277
Glenn Kastend848eb42016-03-08 13:42:11 -08002278audio_session_t MediaPlayerService::AudioOutput::getSessionId() const
Eric Laurent8c563ed2010-10-07 18:23:03 -07002279{
Andy Hungd1c74342015-07-07 16:54:23 -07002280 Mutex::Autolock lock(mLock);
Eric Laurent8c563ed2010-10-07 18:23:03 -07002281 return mSessionId;
2282}
2283
Eric Laurent6f59db12013-07-26 17:16:50 -07002284uint32_t MediaPlayerService::AudioOutput::getSampleRate() const
2285{
Andy Hungd1c74342015-07-07 16:54:23 -07002286 Mutex::Autolock lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -07002287 if (mTrack == 0) return 0;
2288 return mTrack->getSampleRate();
2289}
2290
Andy Hungf2c87b32016-04-07 19:49:29 -07002291int64_t MediaPlayerService::AudioOutput::getBufferDurationInUs() const
2292{
2293 Mutex::Autolock lock(mLock);
2294 if (mTrack == 0) {
2295 return 0;
2296 }
2297 int64_t duration;
2298 if (mTrack->getBufferDurationInUs(&duration) != OK) {
2299 return 0;
2300 }
2301 return duration;
2302}
2303
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002304////////////////////////////////////////////////////////////////////////////////
2305
2306struct CallbackThread : public Thread {
2307 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
2308 MediaPlayerBase::AudioSink::AudioCallback cb,
2309 void *cookie);
2310
2311protected:
2312 virtual ~CallbackThread();
2313
2314 virtual bool threadLoop();
2315
2316private:
2317 wp<MediaPlayerBase::AudioSink> mSink;
2318 MediaPlayerBase::AudioSink::AudioCallback mCallback;
2319 void *mCookie;
2320 void *mBuffer;
2321 size_t mBufferSize;
2322
2323 CallbackThread(const CallbackThread &);
2324 CallbackThread &operator=(const CallbackThread &);
2325};
2326
2327CallbackThread::CallbackThread(
2328 const wp<MediaPlayerBase::AudioSink> &sink,
2329 MediaPlayerBase::AudioSink::AudioCallback cb,
2330 void *cookie)
2331 : mSink(sink),
2332 mCallback(cb),
2333 mCookie(cookie),
2334 mBuffer(NULL),
2335 mBufferSize(0) {
2336}
2337
2338CallbackThread::~CallbackThread() {
2339 if (mBuffer) {
2340 free(mBuffer);
2341 mBuffer = NULL;
2342 }
2343}
2344
2345bool CallbackThread::threadLoop() {
2346 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
2347 if (sink == NULL) {
2348 return false;
2349 }
2350
2351 if (mBuffer == NULL) {
2352 mBufferSize = sink->bufferSize();
2353 mBuffer = malloc(mBufferSize);
2354 }
2355
2356 size_t actualSize =
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002357 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie,
2358 MediaPlayerBase::AudioSink::CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002359
2360 if (actualSize > 0) {
2361 sink->write(mBuffer, actualSize);
Andy Hunga31335a2014-08-20 17:37:59 -07002362 // Could return false on sink->write() error or short count.
2363 // Not necessarily appropriate but would work for AudioCache behavior.
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002364 }
2365
2366 return true;
2367}
2368
2369////////////////////////////////////////////////////////////////////////////////
2370
Gloria Wang7cf180c2011-02-19 18:37:57 -08002371void MediaPlayerService::addBatteryData(uint32_t params)
2372{
2373 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002374
2375 int32_t time = systemTime() / 1000000L;
2376
2377 // change audio output devices. This notification comes from AudioFlinger
2378 if ((params & kBatteryDataSpeakerOn)
2379 || (params & kBatteryDataOtherAudioDeviceOn)) {
2380
2381 int deviceOn[NUM_AUDIO_DEVICES];
2382 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2383 deviceOn[i] = 0;
2384 }
2385
2386 if ((params & kBatteryDataSpeakerOn)
2387 && (params & kBatteryDataOtherAudioDeviceOn)) {
2388 deviceOn[SPEAKER_AND_OTHER] = 1;
2389 } else if (params & kBatteryDataSpeakerOn) {
2390 deviceOn[SPEAKER] = 1;
2391 } else {
2392 deviceOn[OTHER_AUDIO_DEVICE] = 1;
2393 }
2394
2395 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2396 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
2397
2398 if (mBatteryAudio.refCount > 0) { // if playing audio
2399 if (!deviceOn[i]) {
2400 mBatteryAudio.lastTime[i] += time;
2401 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2402 mBatteryAudio.lastTime[i] = 0;
2403 } else {
2404 mBatteryAudio.lastTime[i] = 0 - time;
2405 }
2406 }
2407
2408 mBatteryAudio.deviceOn[i] = deviceOn[i];
2409 }
2410 }
2411 return;
2412 }
2413
Marco Nelissenb7848f12014-12-04 08:57:56 -08002414 // an audio stream is started
Gloria Wang9ee159b2011-02-24 14:51:45 -08002415 if (params & kBatteryDataAudioFlingerStart) {
2416 // record the start time only if currently no other audio
2417 // is being played
2418 if (mBatteryAudio.refCount == 0) {
2419 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2420 if (mBatteryAudio.deviceOn[i]) {
2421 mBatteryAudio.lastTime[i] -= time;
2422 }
2423 }
2424 }
2425
2426 mBatteryAudio.refCount ++;
2427 return;
2428
2429 } else if (params & kBatteryDataAudioFlingerStop) {
2430 if (mBatteryAudio.refCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002431 ALOGW("Battery track warning: refCount is <= 0");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002432 return;
2433 }
2434
2435 // record the stop time only if currently this is the only
2436 // audio being played
2437 if (mBatteryAudio.refCount == 1) {
2438 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2439 if (mBatteryAudio.deviceOn[i]) {
2440 mBatteryAudio.lastTime[i] += time;
2441 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2442 mBatteryAudio.lastTime[i] = 0;
2443 }
2444 }
2445 }
2446
2447 mBatteryAudio.refCount --;
2448 return;
2449 }
2450
Andy Hung1afd0982016-11-08 16:13:44 -08002451 uid_t uid = IPCThreadState::self()->getCallingUid();
Gloria Wang7cf180c2011-02-19 18:37:57 -08002452 if (uid == AID_MEDIA) {
2453 return;
2454 }
2455 int index = mBatteryData.indexOfKey(uid);
Gloria Wang7cf180c2011-02-19 18:37:57 -08002456
2457 if (index < 0) { // create a new entry for this UID
2458 BatteryUsageInfo info;
2459 info.audioTotalTime = 0;
2460 info.videoTotalTime = 0;
2461 info.audioLastTime = 0;
2462 info.videoLastTime = 0;
2463 info.refCount = 0;
2464
Gloria Wang9ee159b2011-02-24 14:51:45 -08002465 if (mBatteryData.add(uid, info) == NO_MEMORY) {
Steve Block29357bc2012-01-06 19:20:56 +00002466 ALOGE("Battery track error: no memory for new app");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002467 return;
2468 }
Gloria Wang7cf180c2011-02-19 18:37:57 -08002469 }
2470
2471 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
2472
2473 if (params & kBatteryDataCodecStarted) {
2474 if (params & kBatteryDataTrackAudio) {
2475 info.audioLastTime -= time;
2476 info.refCount ++;
2477 }
2478 if (params & kBatteryDataTrackVideo) {
2479 info.videoLastTime -= time;
2480 info.refCount ++;
2481 }
2482 } else {
2483 if (info.refCount == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002484 ALOGW("Battery track warning: refCount is already 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002485 return;
2486 } else if (info.refCount < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00002487 ALOGE("Battery track error: refCount < 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002488 mBatteryData.removeItem(uid);
2489 return;
2490 }
2491
2492 if (params & kBatteryDataTrackAudio) {
2493 info.audioLastTime += time;
2494 info.refCount --;
2495 }
2496 if (params & kBatteryDataTrackVideo) {
2497 info.videoLastTime += time;
2498 info.refCount --;
2499 }
2500
2501 // no stream is being played by this UID
2502 if (info.refCount == 0) {
2503 info.audioTotalTime += info.audioLastTime;
2504 info.audioLastTime = 0;
2505 info.videoTotalTime += info.videoLastTime;
2506 info.videoLastTime = 0;
2507 }
2508 }
2509}
2510
2511status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
2512 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002513
2514 // audio output devices usage
2515 int32_t time = systemTime() / 1000000L; //in ms
2516 int32_t totalTime;
2517
2518 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2519 totalTime = mBatteryAudio.totalTime[i];
2520
2521 if (mBatteryAudio.deviceOn[i]
2522 && (mBatteryAudio.lastTime[i] != 0)) {
2523 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
2524 totalTime += tmpTime;
2525 }
2526
2527 reply->writeInt32(totalTime);
2528 // reset the total time
2529 mBatteryAudio.totalTime[i] = 0;
2530 }
2531
2532 // codec usage
Gloria Wang7cf180c2011-02-19 18:37:57 -08002533 BatteryUsageInfo info;
2534 int size = mBatteryData.size();
2535
2536 reply->writeInt32(size);
2537 int i = 0;
2538
2539 while (i < size) {
2540 info = mBatteryData.valueAt(i);
2541
2542 reply->writeInt32(mBatteryData.keyAt(i)); //UID
2543 reply->writeInt32(info.audioTotalTime);
2544 reply->writeInt32(info.videoTotalTime);
2545
2546 info.audioTotalTime = 0;
2547 info.videoTotalTime = 0;
2548
2549 // remove the UID entry where no stream is being played
2550 if (info.refCount <= 0) {
2551 mBatteryData.removeItemsAt(i);
2552 size --;
2553 i --;
2554 }
2555 i++;
2556 }
2557 return NO_ERROR;
2558}
nikoa64c8c72009-07-20 15:07:26 -07002559} // namespace android