blob: dbc7e210396af3a60e65d4a9976b2d616f9f3143 [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 }
Pawin Vongmasa9c47c972017-02-08 04:09:38 -0800600 clearDeathNotifiers();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800601}
602
603void MediaPlayerService::Client::disconnect()
604{
Steve Block3856b092011-10-20 11:56:00 +0100605 ALOGV("disconnect(%d) from pid %d", mConnId, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800606 // grab local reference and clear main reference to prevent future
607 // access to object
608 sp<MediaPlayerBase> p;
609 {
610 Mutex::Autolock l(mLock);
611 p = mPlayer;
beanzdcfefde2012-11-05 09:51:43 +0800612 mClient.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800613 }
Andreas Huber20111aa2009-07-14 16:56:47 -0700614
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800615 mPlayer.clear();
616
617 // clear the notification to prevent callbacks to dead client
618 // and reset the player. We assume the player will serialize
619 // access to itself if necessary.
620 if (p != 0) {
621 p->setNotifyCallback(0, 0);
622#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000623 ALOGD("kill Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800624 mAntagonizer->kill();
625#endif
626 p->reset();
627 }
628
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700629 disconnectNativeWindow();
630
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800631 IPCThreadState::self()->flushCommands();
632}
633
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800634sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
635{
636 // determine if we have the right player type
637 sp<MediaPlayerBase> p = mPlayer;
638 if ((p != NULL) && (p->playerType() != playerType)) {
Steve Block3856b092011-10-20 11:56:00 +0100639 ALOGV("delete player");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800640 p.clear();
641 }
642 if (p == NULL) {
Ronghua Wu68845c12015-07-21 09:50:48 -0700643 p = MediaPlayerFactory::createPlayer(playerType, this, notify, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800644 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700645
Jason Simmonsdb29e522011-08-12 13:46:55 -0700646 if (p != NULL) {
Andy Hung1afd0982016-11-08 16:13:44 -0800647 p->setUID(mUid);
Jason Simmonsdb29e522011-08-12 13:46:55 -0700648 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700649
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800650 return p;
651}
652
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700653MediaPlayerService::Client::ServiceDeathNotifier::ServiceDeathNotifier(
654 const sp<IBinder>& service,
655 const sp<MediaPlayerBase>& listener,
656 int which) {
657 mService = service;
Pawin Vongmasa9c47c972017-02-08 04:09:38 -0800658 mOmx = nullptr;
659 mListener = listener;
660 mWhich = which;
661}
662
663MediaPlayerService::Client::ServiceDeathNotifier::ServiceDeathNotifier(
664 const sp<IOmx>& omx,
665 const sp<MediaPlayerBase>& listener,
666 int which) {
667 mService = nullptr;
668 mOmx = omx;
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700669 mListener = listener;
670 mWhich = which;
671}
672
673MediaPlayerService::Client::ServiceDeathNotifier::~ServiceDeathNotifier() {
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700674}
675
676void MediaPlayerService::Client::ServiceDeathNotifier::binderDied(const wp<IBinder>& /*who*/) {
677 sp<MediaPlayerBase> listener = mListener.promote();
678 if (listener != NULL) {
679 listener->sendEvent(MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED, mWhich);
680 } else {
681 ALOGW("listener for process %d death is gone", mWhich);
682 }
683}
684
Pawin Vongmasa9c47c972017-02-08 04:09:38 -0800685void MediaPlayerService::Client::ServiceDeathNotifier::serviceDied(
686 uint64_t /* cookie */,
687 const wp<::android::hidl::base::V1_0::IBase>& /* who */) {
688 sp<MediaPlayerBase> listener = mListener.promote();
689 if (listener != NULL) {
690 listener->sendEvent(MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED, mWhich);
691 } else {
692 ALOGW("listener for process %d death is gone", mWhich);
693 }
694}
695
696void MediaPlayerService::Client::ServiceDeathNotifier::unlinkToDeath() {
697 if (mService != nullptr) {
698 mService->unlinkToDeath(this);
699 mService = nullptr;
700 } else if (mOmx != nullptr) {
701 mOmx->unlinkToDeath(this);
702 mOmx = nullptr;
703 }
704}
705
706void MediaPlayerService::Client::clearDeathNotifiers() {
707 if (mExtractorDeathListener != nullptr) {
708 mExtractorDeathListener->unlinkToDeath();
709 mExtractorDeathListener = nullptr;
710 }
711 if (mCodecDeathListener != nullptr) {
712 mCodecDeathListener->unlinkToDeath();
713 mCodecDeathListener = nullptr;
714 }
715}
716
John Grossmanc795b642012-02-22 15:38:35 -0800717sp<MediaPlayerBase> MediaPlayerService::Client::setDataSource_pre(
718 player_type playerType)
719{
720 ALOGV("player type = %d", playerType);
Pawin Vongmasa9c47c972017-02-08 04:09:38 -0800721 clearDeathNotifiers();
John Grossmanc795b642012-02-22 15:38:35 -0800722
723 // create the right type of player
724 sp<MediaPlayerBase> p = createPlayer(playerType);
725 if (p == NULL) {
726 return p;
727 }
728
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700729 sp<IServiceManager> sm = defaultServiceManager();
730 sp<IBinder> binder = sm->getService(String16("media.extractor"));
Marco Nelissen1b5a7ee2016-09-30 13:54:30 -0700731 if (binder == NULL) {
732 ALOGE("extractor service not available");
733 return NULL;
734 }
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700735 mExtractorDeathListener = new ServiceDeathNotifier(binder, p, MEDIAEXTRACTOR_PROCESS_DEATH);
736 binder->linkToDeath(mExtractorDeathListener);
737
Pawin Vongmasa9c47c972017-02-08 04:09:38 -0800738 int32_t trebleOmx = property_get_int32("persist.media.treble_omx", -1);
739 if ((trebleOmx == 1) || ((trebleOmx == -1) &&
740 property_get_bool("persist.hal.binderization", 0))) {
741 // Treble IOmx
742 sp<IOmx> omx = IOmx::getService();
743 if (omx == nullptr) {
744 ALOGE("Treble IOmx not available");
745 return NULL;
746 }
747 mCodecDeathListener = new ServiceDeathNotifier(omx, p, MEDIACODEC_PROCESS_DEATH);
748 omx->linkToDeath(mCodecDeathListener, 0);
749 } else {
750 // Legacy IOMX
751 binder = sm->getService(String16("media.codec"));
752 if (binder == NULL) {
753 ALOGE("codec service not available");
754 return NULL;
755 }
756 mCodecDeathListener = new ServiceDeathNotifier(binder, p, MEDIACODEC_PROCESS_DEATH);
757 binder->linkToDeath(mCodecDeathListener);
Marco Nelissen1b5a7ee2016-09-30 13:54:30 -0700758 }
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700759
John Grossmanc795b642012-02-22 15:38:35 -0800760 if (!p->hardwareOutput()) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -0700761 Mutex::Autolock l(mLock);
Marco Nelissend457c972014-02-11 08:47:07 -0800762 mAudioOutput = new AudioOutput(mAudioSessionId, IPCThreadState::self()->getCallingUid(),
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700763 mPid, mAudioAttributes);
John Grossmanc795b642012-02-22 15:38:35 -0800764 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
765 }
766
767 return p;
768}
769
770void MediaPlayerService::Client::setDataSource_post(
771 const sp<MediaPlayerBase>& p,
772 status_t status)
773{
774 ALOGV(" setDataSource");
775 mStatus = status;
776 if (mStatus != OK) {
777 ALOGE(" error: %d", mStatus);
778 return;
779 }
780
781 // Set the re-transmission endpoint if one was chosen.
782 if (mRetransmitEndpointValid) {
783 mStatus = p->setRetransmitEndpoint(&mRetransmitEndpoint);
784 if (mStatus != NO_ERROR) {
785 ALOGE("setRetransmitEndpoint error: %d", mStatus);
786 }
787 }
788
789 if (mStatus == OK) {
790 mPlayer = p;
791 }
792}
793
Andreas Huber2db84552010-01-28 11:19:57 -0800794status_t MediaPlayerService::Client::setDataSource(
Andreas Huber1b86fe02014-01-29 11:13:26 -0800795 const sp<IMediaHTTPService> &httpService,
796 const char *url,
797 const KeyedVector<String8, String8> *headers)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800798{
Steve Block3856b092011-10-20 11:56:00 +0100799 ALOGV("setDataSource(%s)", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800800 if (url == NULL)
801 return UNKNOWN_ERROR;
802
Dave Burked681bbb2011-08-30 14:39:17 +0100803 if ((strncmp(url, "http://", 7) == 0) ||
804 (strncmp(url, "https://", 8) == 0) ||
805 (strncmp(url, "rtsp://", 7) == 0)) {
806 if (!checkPermission("android.permission.INTERNET")) {
807 return PERMISSION_DENIED;
808 }
809 }
810
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800811 if (strncmp(url, "content://", 10) == 0) {
812 // get a filedescriptor for the content Uri and
813 // pass it to the setDataSource(fd) method
814
815 String16 url16(url);
816 int fd = android::openContentProviderFile(url16);
817 if (fd < 0)
818 {
Steve Block29357bc2012-01-06 19:20:56 +0000819 ALOGE("Couldn't open fd for %s", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800820 return UNKNOWN_ERROR;
821 }
822 setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
823 close(fd);
824 return mStatus;
825 } else {
John Grossman44a7e422012-06-21 17:29:24 -0700826 player_type playerType = MediaPlayerFactory::getPlayerType(this, url);
John Grossmanc795b642012-02-22 15:38:35 -0800827 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
828 if (p == NULL) {
829 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800830 }
831
Andreas Huber1b86fe02014-01-29 11:13:26 -0800832 setDataSource_post(p, p->setDataSource(httpService, url, headers));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800833 return mStatus;
834 }
835}
836
837status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
838{
Marco Nelissen83b0fd92015-09-16 13:48:07 -0700839 ALOGV("setDataSource fd=%d (%s), offset=%lld, length=%lld",
840 fd, nameForFd(fd).c_str(), (long long) offset, (long long) length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800841 struct stat sb;
842 int ret = fstat(fd, &sb);
843 if (ret != 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000844 ALOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800845 return UNKNOWN_ERROR;
846 }
847
Andy Hung833b4752016-04-04 17:15:48 -0700848 ALOGV("st_dev = %llu", static_cast<unsigned long long>(sb.st_dev));
Steve Block3856b092011-10-20 11:56:00 +0100849 ALOGV("st_mode = %u", sb.st_mode);
Mark Salyzyn77342f72014-06-18 16:31:32 -0700850 ALOGV("st_uid = %lu", static_cast<unsigned long>(sb.st_uid));
851 ALOGV("st_gid = %lu", static_cast<unsigned long>(sb.st_gid));
Andy Hung833b4752016-04-04 17:15:48 -0700852 ALOGV("st_size = %llu", static_cast<unsigned long long>(sb.st_size));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800853
854 if (offset >= sb.st_size) {
Steve Block29357bc2012-01-06 19:20:56 +0000855 ALOGE("offset error");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800856 return UNKNOWN_ERROR;
857 }
858 if (offset + length > sb.st_size) {
859 length = sb.st_size - offset;
Andy Hung833b4752016-04-04 17:15:48 -0700860 ALOGV("calculated length = %lld", (long long)length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800861 }
862
John Grossman44a7e422012-06-21 17:29:24 -0700863 player_type playerType = MediaPlayerFactory::getPlayerType(this,
864 fd,
865 offset,
866 length);
John Grossmanc795b642012-02-22 15:38:35 -0800867 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
868 if (p == NULL) {
869 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800870 }
871
872 // now set data source
John Grossmanc795b642012-02-22 15:38:35 -0800873 setDataSource_post(p, p->setDataSource(fd, offset, length));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800874 return mStatus;
875}
876
Andreas Hubere2b10282010-11-23 11:41:34 -0800877status_t MediaPlayerService::Client::setDataSource(
878 const sp<IStreamSource> &source) {
879 // create the right type of player
John Grossman44a7e422012-06-21 17:29:24 -0700880 player_type playerType = MediaPlayerFactory::getPlayerType(this, source);
John Grossmanc795b642012-02-22 15:38:35 -0800881 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
Andreas Hubere2b10282010-11-23 11:41:34 -0800882 if (p == NULL) {
883 return NO_INIT;
884 }
885
Andreas Hubere2b10282010-11-23 11:41:34 -0800886 // now set data source
John Grossmanc795b642012-02-22 15:38:35 -0800887 setDataSource_post(p, p->setDataSource(source));
Andreas Hubere2b10282010-11-23 11:41:34 -0800888 return mStatus;
889}
890
Chris Watkins99f31602015-03-20 13:06:33 -0700891status_t MediaPlayerService::Client::setDataSource(
892 const sp<IDataSource> &source) {
893 sp<DataSource> dataSource = DataSource::CreateFromIDataSource(source);
894 player_type playerType = MediaPlayerFactory::getPlayerType(this, dataSource);
895 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
896 if (p == NULL) {
897 return NO_INIT;
898 }
899 // now set data source
900 setDataSource_post(p, p->setDataSource(dataSource));
901 return mStatus;
902}
903
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700904void MediaPlayerService::Client::disconnectNativeWindow() {
905 if (mConnectedWindow != NULL) {
906 status_t err = native_window_api_disconnect(mConnectedWindow.get(),
907 NATIVE_WINDOW_API_MEDIA);
908
909 if (err != OK) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000910 ALOGW("native_window_api_disconnect returned an error: %s (%d)",
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700911 strerror(-err), err);
912 }
913 }
914 mConnectedWindow.clear();
915}
916
Glenn Kasten11731182011-02-08 17:26:17 -0800917status_t MediaPlayerService::Client::setVideoSurfaceTexture(
Andy McFadden484566c2012-12-18 09:46:54 -0800918 const sp<IGraphicBufferProducer>& bufferProducer)
Glenn Kasten11731182011-02-08 17:26:17 -0800919{
Andy McFadden484566c2012-12-18 09:46:54 -0800920 ALOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, bufferProducer.get());
Glenn Kasten11731182011-02-08 17:26:17 -0800921 sp<MediaPlayerBase> p = getPlayer();
922 if (p == 0) return UNKNOWN_ERROR;
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700923
Marco Nelissenf8880202014-11-14 07:58:25 -0800924 sp<IBinder> binder(IInterface::asBinder(bufferProducer));
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700925 if (mConnectedWindowBinder == binder) {
926 return OK;
927 }
928
929 sp<ANativeWindow> anw;
Andy McFadden484566c2012-12-18 09:46:54 -0800930 if (bufferProducer != NULL) {
Marco Nelissenee08f7e2013-09-16 13:30:01 -0700931 anw = new Surface(bufferProducer, true /* controlledByApp */);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700932 status_t err = native_window_api_connect(anw.get(),
933 NATIVE_WINDOW_API_MEDIA);
934
935 if (err != OK) {
Steve Block29357bc2012-01-06 19:20:56 +0000936 ALOGE("setVideoSurfaceTexture failed: %d", err);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700937 // Note that we must do the reset before disconnecting from the ANW.
938 // Otherwise queue/dequeue calls could be made on the disconnected
939 // ANW, which may result in errors.
940 reset();
941
942 disconnectNativeWindow();
943
944 return err;
945 }
946 }
947
Andy McFadden484566c2012-12-18 09:46:54 -0800948 // Note that we must set the player's new GraphicBufferProducer before
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700949 // disconnecting the old one. Otherwise queue/dequeue calls could be made
950 // on the disconnected ANW, which may result in errors.
Andy McFadden484566c2012-12-18 09:46:54 -0800951 status_t err = p->setVideoSurfaceTexture(bufferProducer);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700952
953 disconnectNativeWindow();
954
955 mConnectedWindow = anw;
956
957 if (err == OK) {
958 mConnectedWindowBinder = binder;
959 } else {
960 disconnectNativeWindow();
961 }
962
963 return err;
Glenn Kasten11731182011-02-08 17:26:17 -0800964}
965
Nicolas Catania1d187f12009-05-12 23:25:55 -0700966status_t MediaPlayerService::Client::invoke(const Parcel& request,
967 Parcel *reply)
968{
969 sp<MediaPlayerBase> p = getPlayer();
970 if (p == NULL) return UNKNOWN_ERROR;
971 return p->invoke(request, reply);
972}
973
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700974// This call doesn't need to access the native player.
975status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
976{
977 status_t status;
nikoa64c8c72009-07-20 15:07:26 -0700978 media::Metadata::Filter allow, drop;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700979
Nicolas Catania48290382009-07-10 13:53:06 -0700980 if (unmarshallFilter(filter, &allow, &status) &&
981 unmarshallFilter(filter, &drop, &status)) {
982 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700983
984 mMetadataAllow = allow;
985 mMetadataDrop = drop;
986 }
987 return status;
988}
989
Nicolas Catania48290382009-07-10 13:53:06 -0700990status_t MediaPlayerService::Client::getMetadata(
Mark Salyzyn77342f72014-06-18 16:31:32 -0700991 bool update_only, bool /*apply_filter*/, Parcel *reply)
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700992{
nikoa64c8c72009-07-20 15:07:26 -0700993 sp<MediaPlayerBase> player = getPlayer();
994 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania48290382009-07-10 13:53:06 -0700995
nikod608a812009-07-16 16:39:53 -0700996 status_t status;
997 // Placeholder for the return code, updated by the caller.
998 reply->writeInt32(-1);
999
nikoa64c8c72009-07-20 15:07:26 -07001000 media::Metadata::Filter ids;
Nicolas Catania48290382009-07-10 13:53:06 -07001001
1002 // We don't block notifications while we fetch the data. We clear
1003 // mMetadataUpdated first so we don't lose notifications happening
1004 // during the rest of this call.
1005 {
1006 Mutex::Autolock lock(mLock);
1007 if (update_only) {
nikod608a812009-07-16 16:39:53 -07001008 ids = mMetadataUpdated;
Nicolas Catania48290382009-07-10 13:53:06 -07001009 }
1010 mMetadataUpdated.clear();
1011 }
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001012
nikoa64c8c72009-07-20 15:07:26 -07001013 media::Metadata metadata(reply);
Nicolas Catania48290382009-07-10 13:53:06 -07001014
nikoa64c8c72009-07-20 15:07:26 -07001015 metadata.appendHeader();
1016 status = player->getMetadata(ids, reply);
nikod608a812009-07-16 16:39:53 -07001017
1018 if (status != OK) {
nikoa64c8c72009-07-20 15:07:26 -07001019 metadata.resetParcel();
Steve Block29357bc2012-01-06 19:20:56 +00001020 ALOGE("getMetadata failed %d", status);
nikod608a812009-07-16 16:39:53 -07001021 return status;
1022 }
1023
1024 // FIXME: Implement filtering on the result. Not critical since
1025 // filtering takes place on the update notifications already. This
1026 // would be when all the metadata are fetch and a filter is set.
1027
nikod608a812009-07-16 16:39:53 -07001028 // Everything is fine, update the metadata length.
nikoa64c8c72009-07-20 15:07:26 -07001029 metadata.updateLength();
nikod608a812009-07-16 16:39:53 -07001030 return OK;
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001031}
1032
Wei Jiad399e7e2016-10-26 15:49:11 -07001033status_t MediaPlayerService::Client::setBufferingSettings(
1034 const BufferingSettings& buffering)
1035{
Wei Jiadc6f3402017-01-09 15:04:18 -08001036 ALOGV("[%d] setBufferingSettings{%s}",
1037 mConnId, buffering.toString().string());
Wei Jiad399e7e2016-10-26 15:49:11 -07001038 sp<MediaPlayerBase> p = getPlayer();
1039 if (p == 0) return UNKNOWN_ERROR;
1040 return p->setBufferingSettings(buffering);
1041}
1042
1043status_t MediaPlayerService::Client::getDefaultBufferingSettings(
1044 BufferingSettings* buffering /* nonnull */)
1045{
1046 sp<MediaPlayerBase> p = getPlayer();
1047 // TODO: create mPlayer on demand.
1048 if (p == 0) return UNKNOWN_ERROR;
1049 status_t ret = p->getDefaultBufferingSettings(buffering);
1050 if (ret == NO_ERROR) {
Wei Jiadc6f3402017-01-09 15:04:18 -08001051 ALOGV("[%d] getDefaultBufferingSettings{%s}",
1052 mConnId, buffering->toString().string());
Wei Jiad399e7e2016-10-26 15:49:11 -07001053 } else {
1054 ALOGV("[%d] getDefaultBufferingSettings returned %d", mConnId, ret);
1055 }
1056 return ret;
1057}
1058
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001059status_t MediaPlayerService::Client::prepareAsync()
1060{
Steve Block3856b092011-10-20 11:56:00 +01001061 ALOGV("[%d] prepareAsync", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001062 sp<MediaPlayerBase> p = getPlayer();
1063 if (p == 0) return UNKNOWN_ERROR;
1064 status_t ret = p->prepareAsync();
1065#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +00001066 ALOGD("start Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001067 if (ret == NO_ERROR) mAntagonizer->start();
1068#endif
1069 return ret;
1070}
1071
1072status_t MediaPlayerService::Client::start()
1073{
Steve Block3856b092011-10-20 11:56:00 +01001074 ALOGV("[%d] start", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001075 sp<MediaPlayerBase> p = getPlayer();
1076 if (p == 0) return UNKNOWN_ERROR;
1077 p->setLooping(mLoop);
1078 return p->start();
1079}
1080
1081status_t MediaPlayerService::Client::stop()
1082{
Steve Block3856b092011-10-20 11:56:00 +01001083 ALOGV("[%d] stop", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001084 sp<MediaPlayerBase> p = getPlayer();
1085 if (p == 0) return UNKNOWN_ERROR;
1086 return p->stop();
1087}
1088
1089status_t MediaPlayerService::Client::pause()
1090{
Steve Block3856b092011-10-20 11:56:00 +01001091 ALOGV("[%d] pause", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001092 sp<MediaPlayerBase> p = getPlayer();
1093 if (p == 0) return UNKNOWN_ERROR;
1094 return p->pause();
1095}
1096
1097status_t MediaPlayerService::Client::isPlaying(bool* state)
1098{
1099 *state = false;
1100 sp<MediaPlayerBase> p = getPlayer();
1101 if (p == 0) return UNKNOWN_ERROR;
1102 *state = p->isPlaying();
Steve Block3856b092011-10-20 11:56:00 +01001103 ALOGV("[%d] isPlaying: %d", mConnId, *state);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001104 return NO_ERROR;
1105}
1106
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001107status_t MediaPlayerService::Client::setPlaybackSettings(const AudioPlaybackRate& rate)
Wei Jia98160162015-02-04 17:01:11 -08001108{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001109 ALOGV("[%d] setPlaybackSettings(%f, %f, %d, %d)",
1110 mConnId, rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Wei Jia98160162015-02-04 17:01:11 -08001111 sp<MediaPlayerBase> p = getPlayer();
1112 if (p == 0) return UNKNOWN_ERROR;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001113 return p->setPlaybackSettings(rate);
1114}
1115
1116status_t MediaPlayerService::Client::getPlaybackSettings(AudioPlaybackRate* rate /* nonnull */)
1117{
1118 sp<MediaPlayerBase> p = getPlayer();
1119 if (p == 0) return UNKNOWN_ERROR;
1120 status_t ret = p->getPlaybackSettings(rate);
1121 if (ret == NO_ERROR) {
1122 ALOGV("[%d] getPlaybackSettings(%f, %f, %d, %d)",
1123 mConnId, rate->mSpeed, rate->mPitch, rate->mFallbackMode, rate->mStretchMode);
1124 } else {
1125 ALOGV("[%d] getPlaybackSettings returned %d", mConnId, ret);
1126 }
1127 return ret;
1128}
1129
1130status_t MediaPlayerService::Client::setSyncSettings(
1131 const AVSyncSettings& sync, float videoFpsHint)
1132{
1133 ALOGV("[%d] setSyncSettings(%u, %u, %f, %f)",
1134 mConnId, sync.mSource, sync.mAudioAdjustMode, sync.mTolerance, videoFpsHint);
1135 sp<MediaPlayerBase> p = getPlayer();
1136 if (p == 0) return UNKNOWN_ERROR;
1137 return p->setSyncSettings(sync, videoFpsHint);
1138}
1139
1140status_t MediaPlayerService::Client::getSyncSettings(
1141 AVSyncSettings* sync /* nonnull */, float* videoFps /* nonnull */)
1142{
1143 sp<MediaPlayerBase> p = getPlayer();
1144 if (p == 0) return UNKNOWN_ERROR;
1145 status_t ret = p->getSyncSettings(sync, videoFps);
1146 if (ret == NO_ERROR) {
1147 ALOGV("[%d] getSyncSettings(%u, %u, %f, %f)",
1148 mConnId, sync->mSource, sync->mAudioAdjustMode, sync->mTolerance, *videoFps);
1149 } else {
1150 ALOGV("[%d] getSyncSettings returned %d", mConnId, ret);
1151 }
1152 return ret;
Wei Jia98160162015-02-04 17:01:11 -08001153}
1154
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001155status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
1156{
Steve Block3856b092011-10-20 11:56:00 +01001157 ALOGV("getCurrentPosition");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001158 sp<MediaPlayerBase> p = getPlayer();
1159 if (p == 0) return UNKNOWN_ERROR;
1160 status_t ret = p->getCurrentPosition(msec);
1161 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001162 ALOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001163 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001164 ALOGE("getCurrentPosition returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001165 }
1166 return ret;
1167}
1168
1169status_t MediaPlayerService::Client::getDuration(int *msec)
1170{
Steve Block3856b092011-10-20 11:56:00 +01001171 ALOGV("getDuration");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001172 sp<MediaPlayerBase> p = getPlayer();
1173 if (p == 0) return UNKNOWN_ERROR;
1174 status_t ret = p->getDuration(msec);
1175 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001176 ALOGV("[%d] getDuration = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001177 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001178 ALOGE("getDuration returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001179 }
1180 return ret;
1181}
1182
Marco Nelissen6b74d672012-02-28 16:07:44 -08001183status_t MediaPlayerService::Client::setNextPlayer(const sp<IMediaPlayer>& player) {
1184 ALOGV("setNextPlayer");
1185 Mutex::Autolock l(mLock);
1186 sp<Client> c = static_cast<Client*>(player.get());
Wei Jia28284122016-08-30 13:49:06 -07001187 if (c != NULL && !mService->hasClient(c)) {
Robert Shihee0a0e32016-08-16 16:50:54 -07001188 return BAD_VALUE;
1189 }
1190
Marco Nelissen6b74d672012-02-28 16:07:44 -08001191 mNextClient = c;
John Grossman5f7e55e2012-08-24 14:47:25 -07001192
1193 if (c != NULL) {
1194 if (mAudioOutput != NULL) {
1195 mAudioOutput->setNextOutput(c->mAudioOutput);
1196 } else if ((mPlayer != NULL) && !mPlayer->hardwareOutput()) {
1197 ALOGE("no current audio output");
1198 }
1199
1200 if ((mPlayer != NULL) && (mNextClient->getPlayer() != NULL)) {
1201 mPlayer->setNextPlayer(mNextClient->getPlayer());
1202 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001203 }
John Grossman5f7e55e2012-08-24 14:47:25 -07001204
Marco Nelissen6b74d672012-02-28 16:07:44 -08001205 return OK;
1206}
1207
Andy Hung9fc8b5c2017-01-24 13:36:48 -08001208VolumeShaper::Status MediaPlayerService::Client::applyVolumeShaper(
1209 const sp<VolumeShaper::Configuration>& configuration,
1210 const sp<VolumeShaper::Operation>& operation) {
1211 // for hardware output, call player instead
1212 ALOGV("Client::applyVolumeShaper(%p)", this);
1213 sp<MediaPlayerBase> p = getPlayer();
1214 {
1215 Mutex::Autolock l(mLock);
1216 if (p != 0 && p->hardwareOutput()) {
1217 // TODO: investigate internal implementation
1218 return VolumeShaper::Status(INVALID_OPERATION);
1219 }
1220 if (mAudioOutput.get() != nullptr) {
1221 return mAudioOutput->applyVolumeShaper(configuration, operation);
1222 }
1223 }
1224 return VolumeShaper::Status(INVALID_OPERATION);
1225}
1226
1227sp<VolumeShaper::State> MediaPlayerService::Client::getVolumeShaperState(int id) {
1228 // for hardware output, call player instead
1229 ALOGV("Client::getVolumeShaperState(%p)", this);
1230 sp<MediaPlayerBase> p = getPlayer();
1231 {
1232 Mutex::Autolock l(mLock);
1233 if (p != 0 && p->hardwareOutput()) {
1234 // TODO: investigate internal implementation.
1235 return nullptr;
1236 }
1237 if (mAudioOutput.get() != nullptr) {
1238 return mAudioOutput->getVolumeShaperState(id);
1239 }
1240 }
1241 return nullptr;
1242}
1243
Wei Jiac5de0912016-11-18 10:22:14 -08001244status_t MediaPlayerService::Client::seekTo(int msec, MediaPlayerSeekMode mode)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001245{
Wei Jiac5de0912016-11-18 10:22:14 -08001246 ALOGV("[%d] seekTo(%d, %d)", mConnId, msec, mode);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001247 sp<MediaPlayerBase> p = getPlayer();
1248 if (p == 0) return UNKNOWN_ERROR;
Wei Jiac5de0912016-11-18 10:22:14 -08001249 return p->seekTo(msec, mode);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001250}
1251
1252status_t MediaPlayerService::Client::reset()
1253{
Steve Block3856b092011-10-20 11:56:00 +01001254 ALOGV("[%d] reset", mConnId);
John Grossmanc795b642012-02-22 15:38:35 -08001255 mRetransmitEndpointValid = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001256 sp<MediaPlayerBase> p = getPlayer();
1257 if (p == 0) return UNKNOWN_ERROR;
1258 return p->reset();
1259}
1260
Glenn Kastenfff6d712012-01-12 16:38:12 -08001261status_t MediaPlayerService::Client::setAudioStreamType(audio_stream_type_t type)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001262{
Steve Block3856b092011-10-20 11:56:00 +01001263 ALOGV("[%d] setAudioStreamType(%d)", mConnId, type);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001264 // TODO: for hardware output, call player instead
1265 Mutex::Autolock l(mLock);
1266 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1267 return NO_ERROR;
1268}
1269
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001270status_t MediaPlayerService::Client::setAudioAttributes_l(const Parcel &parcel)
1271{
1272 if (mAudioAttributes != NULL) { free(mAudioAttributes); }
1273 mAudioAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001274 if (mAudioAttributes == NULL) {
1275 return NO_MEMORY;
1276 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001277 unmarshallAudioAttributes(parcel, mAudioAttributes);
1278
1279 ALOGV("setAudioAttributes_l() usage=%d content=%d flags=0x%x tags=%s",
1280 mAudioAttributes->usage, mAudioAttributes->content_type, mAudioAttributes->flags,
1281 mAudioAttributes->tags);
1282
1283 if (mAudioOutput != 0) {
1284 mAudioOutput->setAudioAttributes(mAudioAttributes);
1285 }
1286 return NO_ERROR;
1287}
1288
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001289status_t MediaPlayerService::Client::setLooping(int loop)
1290{
Steve Block3856b092011-10-20 11:56:00 +01001291 ALOGV("[%d] setLooping(%d)", mConnId, loop);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001292 mLoop = loop;
1293 sp<MediaPlayerBase> p = getPlayer();
1294 if (p != 0) return p->setLooping(loop);
1295 return NO_ERROR;
1296}
1297
1298status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1299{
Steve Block3856b092011-10-20 11:56:00 +01001300 ALOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
John Grossman761defc2012-02-09 15:09:05 -08001301
1302 // for hardware output, call player instead
1303 sp<MediaPlayerBase> p = getPlayer();
1304 {
1305 Mutex::Autolock l(mLock);
1306 if (p != 0 && p->hardwareOutput()) {
1307 MediaPlayerHWInterface* hwp =
1308 reinterpret_cast<MediaPlayerHWInterface*>(p.get());
1309 return hwp->setVolume(leftVolume, rightVolume);
1310 } else {
1311 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1312 return NO_ERROR;
1313 }
1314 }
1315
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001316 return NO_ERROR;
1317}
1318
Eric Laurent2beeb502010-07-16 07:43:46 -07001319status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1320{
Steve Block3856b092011-10-20 11:56:00 +01001321 ALOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
Eric Laurent2beeb502010-07-16 07:43:46 -07001322 Mutex::Autolock l(mLock);
1323 if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1324 return NO_ERROR;
1325}
1326
1327status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1328{
Steve Block3856b092011-10-20 11:56:00 +01001329 ALOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
Eric Laurent2beeb502010-07-16 07:43:46 -07001330 Mutex::Autolock l(mLock);
1331 if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1332 return NO_ERROR;
1333}
Nicolas Catania48290382009-07-10 13:53:06 -07001334
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001335status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
Steve Block3856b092011-10-20 11:56:00 +01001336 ALOGV("[%d] setParameter(%d)", mConnId, key);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001337 switch (key) {
1338 case KEY_PARAMETER_AUDIO_ATTRIBUTES:
1339 {
1340 Mutex::Autolock l(mLock);
1341 return setAudioAttributes_l(request);
1342 }
1343 default:
1344 sp<MediaPlayerBase> p = getPlayer();
1345 if (p == 0) { return UNKNOWN_ERROR; }
1346 return p->setParameter(key, request);
1347 }
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001348}
1349
1350status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
Steve Block3856b092011-10-20 11:56:00 +01001351 ALOGV("[%d] getParameter(%d)", mConnId, key);
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001352 sp<MediaPlayerBase> p = getPlayer();
1353 if (p == 0) return UNKNOWN_ERROR;
1354 return p->getParameter(key, reply);
1355}
1356
John Grossmanc795b642012-02-22 15:38:35 -08001357status_t MediaPlayerService::Client::setRetransmitEndpoint(
1358 const struct sockaddr_in* endpoint) {
1359
1360 if (NULL != endpoint) {
1361 uint32_t a = ntohl(endpoint->sin_addr.s_addr);
1362 uint16_t p = ntohs(endpoint->sin_port);
1363 ALOGV("[%d] setRetransmitEndpoint(%u.%u.%u.%u:%hu)", mConnId,
1364 (a >> 24), (a >> 16) & 0xFF, (a >> 8) & 0xFF, (a & 0xFF), p);
1365 } else {
1366 ALOGV("[%d] setRetransmitEndpoint = <none>", mConnId);
1367 }
1368
1369 sp<MediaPlayerBase> p = getPlayer();
1370
1371 // Right now, the only valid time to set a retransmit endpoint is before
1372 // player selection has been made (since the presence or absence of a
1373 // retransmit endpoint is going to determine which player is selected during
1374 // setDataSource).
1375 if (p != 0) return INVALID_OPERATION;
1376
1377 if (NULL != endpoint) {
1378 mRetransmitEndpoint = *endpoint;
1379 mRetransmitEndpointValid = true;
1380 } else {
1381 mRetransmitEndpointValid = false;
1382 }
1383
1384 return NO_ERROR;
1385}
1386
John Grossman44a7e422012-06-21 17:29:24 -07001387status_t MediaPlayerService::Client::getRetransmitEndpoint(
1388 struct sockaddr_in* endpoint)
1389{
1390 if (NULL == endpoint)
1391 return BAD_VALUE;
1392
1393 sp<MediaPlayerBase> p = getPlayer();
1394
1395 if (p != NULL)
1396 return p->getRetransmitEndpoint(endpoint);
1397
1398 if (!mRetransmitEndpointValid)
1399 return NO_INIT;
1400
1401 *endpoint = mRetransmitEndpoint;
1402
1403 return NO_ERROR;
1404}
1405
Gloria Wangb483c472011-04-11 17:23:27 -07001406void MediaPlayerService::Client::notify(
1407 void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001408{
1409 Client* client = static_cast<Client*>(cookie);
James Dongb8a98252012-08-26 16:13:03 -07001410 if (client == NULL) {
1411 return;
1412 }
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001413
James Dongb8a98252012-08-26 16:13:03 -07001414 sp<IMediaPlayerClient> c;
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001415 sp<Client> nextClient;
1416 status_t errStartNext = NO_ERROR;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001417 {
1418 Mutex::Autolock l(client->mLock);
James Dongb8a98252012-08-26 16:13:03 -07001419 c = client->mClient;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001420 if (msg == MEDIA_PLAYBACK_COMPLETE && client->mNextClient != NULL) {
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001421 nextClient = client->mNextClient;
1422
John Grossmancb0b7552012-08-23 17:47:31 -07001423 if (client->mAudioOutput != NULL)
1424 client->mAudioOutput->switchToNextOutput();
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001425
1426 errStartNext = nextClient->start();
1427 }
1428 }
1429
1430 if (nextClient != NULL) {
1431 sp<IMediaPlayerClient> nc;
1432 {
1433 Mutex::Autolock l(nextClient->mLock);
1434 nc = nextClient->mClient;
1435 }
1436 if (nc != NULL) {
1437 if (errStartNext == NO_ERROR) {
1438 nc->notify(MEDIA_INFO, MEDIA_INFO_STARTED_AS_NEXT, 0, obj);
1439 } else {
1440 nc->notify(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN , 0, obj);
1441 ALOGE("gapless:start playback for next track failed, err(%d)", errStartNext);
Wei Jia2afac0c2016-01-07 12:13:07 -08001442 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001443 }
1444 }
1445
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001446 if (MEDIA_INFO == msg &&
Nicolas Catania48290382009-07-10 13:53:06 -07001447 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikoa64c8c72009-07-20 15:07:26 -07001448 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania48290382009-07-10 13:53:06 -07001449
1450 if(client->shouldDropMetadata(metadata_type)) {
1451 return;
1452 }
1453
1454 // Update the list of metadata that have changed. getMetadata
1455 // also access mMetadataUpdated and clears it.
1456 client->addNewMetadataUpdate(metadata_type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001457 }
James Dongb8a98252012-08-26 16:13:03 -07001458
1459 if (c != NULL) {
1460 ALOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
1461 c->notify(msg, ext1, ext2, obj);
1462 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001463}
1464
Nicolas Catania48290382009-07-10 13:53:06 -07001465
nikoa64c8c72009-07-20 15:07:26 -07001466bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001467{
Nicolas Catania48290382009-07-10 13:53:06 -07001468 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001469
Nicolas Catania48290382009-07-10 13:53:06 -07001470 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001471 return true;
1472 }
1473
Nicolas Catania48290382009-07-10 13:53:06 -07001474 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001475 return false;
Nicolas Catania48290382009-07-10 13:53:06 -07001476 } else {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001477 return true;
1478 }
1479}
1480
Nicolas Catania48290382009-07-10 13:53:06 -07001481
nikoa64c8c72009-07-20 15:07:26 -07001482void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania48290382009-07-10 13:53:06 -07001483 Mutex::Autolock lock(mLock);
1484 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1485 mMetadataUpdated.add(metadata_type);
1486 }
1487}
1488
Hassan Shojaniacefac142017-02-06 21:02:02 -08001489// Modular DRM
1490status_t MediaPlayerService::Client::prepareDrm(const uint8_t uuid[16],
1491 const Vector<uint8_t>& drmSessionId)
1492{
1493 ALOGV("[%d] prepareDrm", mConnId);
1494 sp<MediaPlayerBase> p = getPlayer();
1495 if (p == 0) return UNKNOWN_ERROR;
1496
1497 status_t ret = p->prepareDrm(uuid, drmSessionId);
1498 ALOGV("prepareDrm ret: %d", ret);
1499
1500 return ret;
1501}
1502
1503status_t MediaPlayerService::Client::releaseDrm()
1504{
1505 ALOGV("[%d] releaseDrm", mConnId);
1506 sp<MediaPlayerBase> p = getPlayer();
1507 if (p == 0) return UNKNOWN_ERROR;
1508
1509 status_t ret = p->releaseDrm();
1510 ALOGV("releaseDrm ret: %d", ret);
1511
1512 return ret;
1513}
1514
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001515#if CALLBACK_ANTAGONIZER
1516const int Antagonizer::interval = 10000; // 10 msecs
1517
1518Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1519 mExit(false), mActive(false), mClient(client), mCb(cb)
1520{
1521 createThread(callbackThread, this);
1522}
1523
1524void Antagonizer::kill()
1525{
1526 Mutex::Autolock _l(mLock);
1527 mActive = false;
1528 mExit = true;
1529 mCondition.wait(mLock);
1530}
1531
1532int Antagonizer::callbackThread(void* user)
1533{
Steve Blockb8a80522011-12-20 16:23:08 +00001534 ALOGD("Antagonizer started");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001535 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1536 while (!p->mExit) {
1537 if (p->mActive) {
Steve Block3856b092011-10-20 11:56:00 +01001538 ALOGV("send event");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001539 p->mCb(p->mClient, 0, 0, 0);
1540 }
1541 usleep(interval);
1542 }
1543 Mutex::Autolock _l(p->mLock);
1544 p->mCondition.signal();
Steve Blockb8a80522011-12-20 16:23:08 +00001545 ALOGD("Antagonizer stopped");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001546 return 0;
1547}
1548#endif
1549
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001550#undef LOG_TAG
1551#define LOG_TAG "AudioSink"
Andy Hung1afd0982016-11-08 16:13:44 -08001552MediaPlayerService::AudioOutput::AudioOutput(audio_session_t sessionId, uid_t uid, int pid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001553 const audio_attributes_t* attr)
Andreas Huber20111aa2009-07-14 16:56:47 -07001554 : mCallback(NULL),
Eric Laurenta514bdb2010-06-21 09:27:30 -07001555 mCallbackCookie(NULL),
Marco Nelissen6b74d672012-02-28 16:07:44 -08001556 mCallbackData(NULL),
Andy Hungd1c74342015-07-07 16:54:23 -07001557 mStreamType(AUDIO_STREAM_MUSIC),
Andy Hungd1c74342015-07-07 16:54:23 -07001558 mLeftVolume(1.0),
1559 mRightVolume(1.0),
1560 mPlaybackRate(AUDIO_PLAYBACK_RATE_DEFAULT),
1561 mSampleRateHz(0),
1562 mMsecsPerFrame(0),
1563 mFrameSize(0),
Eric Laurent1948eb32012-04-13 16:50:19 -07001564 mSessionId(sessionId),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001565 mUid(uid),
Marco Nelissend457c972014-02-11 08:47:07 -08001566 mPid(pid),
Andy Hungd1c74342015-07-07 16:54:23 -07001567 mSendLevel(0.0),
1568 mAuxEffectId(0),
1569 mFlags(AUDIO_OUTPUT_FLAG_NONE)
1570{
Steve Block3856b092011-10-20 11:56:00 +01001571 ALOGV("AudioOutput(%d)", sessionId);
Eric Laurent43562692015-07-15 16:49:07 -07001572 if (attr != NULL) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001573 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1574 if (mAttributes != NULL) {
1575 memcpy(mAttributes, attr, sizeof(audio_attributes_t));
1576 mStreamType = audio_attributes_to_stream_type(attr);
1577 }
1578 } else {
1579 mAttributes = NULL;
Eric Laurent43562692015-07-15 16:49:07 -07001580 }
1581
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001582 setMinBufferCount();
1583}
1584
1585MediaPlayerService::AudioOutput::~AudioOutput()
1586{
1587 close();
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001588 free(mAttributes);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001589 delete mCallbackData;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001590}
1591
Andy Hungd1c74342015-07-07 16:54:23 -07001592//static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001593void MediaPlayerService::AudioOutput::setMinBufferCount()
1594{
1595 char value[PROPERTY_VALUE_MAX];
1596 if (property_get("ro.kernel.qemu", value, 0)) {
1597 mIsOnEmulator = true;
1598 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1599 }
1600}
1601
Andy Hungd1c74342015-07-07 16:54:23 -07001602// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001603bool MediaPlayerService::AudioOutput::isOnEmulator()
1604{
Andy Hungd1c74342015-07-07 16:54:23 -07001605 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001606 return mIsOnEmulator;
1607}
1608
Andy Hungd1c74342015-07-07 16:54:23 -07001609// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001610int MediaPlayerService::AudioOutput::getMinBufferCount()
1611{
Andy Hungd1c74342015-07-07 16:54:23 -07001612 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001613 return mMinBufferCount;
1614}
1615
1616ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1617{
Andy Hungd1c74342015-07-07 16:54:23 -07001618 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001619 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001620 return mTrack->frameCount() * mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001621}
1622
1623ssize_t MediaPlayerService::AudioOutput::frameCount() const
1624{
Andy Hungd1c74342015-07-07 16:54:23 -07001625 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001626 if (mTrack == 0) return NO_INIT;
1627 return mTrack->frameCount();
1628}
1629
1630ssize_t MediaPlayerService::AudioOutput::channelCount() const
1631{
Andy Hungd1c74342015-07-07 16:54:23 -07001632 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001633 if (mTrack == 0) return NO_INIT;
1634 return mTrack->channelCount();
1635}
1636
1637ssize_t MediaPlayerService::AudioOutput::frameSize() const
1638{
Andy Hungd1c74342015-07-07 16:54:23 -07001639 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001640 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001641 return mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001642}
1643
1644uint32_t MediaPlayerService::AudioOutput::latency () const
1645{
Andy Hungd1c74342015-07-07 16:54:23 -07001646 Mutex::Autolock lock(mLock);
Eric Laurentdb354e52012-03-05 17:27:11 -08001647 if (mTrack == 0) return 0;
1648 return mTrack->latency();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001649}
1650
1651float MediaPlayerService::AudioOutput::msecsPerFrame() const
1652{
Andy Hungd1c74342015-07-07 16:54:23 -07001653 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001654 return mMsecsPerFrame;
1655}
1656
Marco Nelissen4110c102012-03-29 09:31:28 -07001657status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position) const
Eric Laurent342e9cf2010-01-19 17:37:09 -08001658{
Andy Hungd1c74342015-07-07 16:54:23 -07001659 Mutex::Autolock lock(mLock);
Eric Laurent342e9cf2010-01-19 17:37:09 -08001660 if (mTrack == 0) return NO_INIT;
1661 return mTrack->getPosition(position);
1662}
1663
Lajos Molnar06ad1522014-08-28 07:27:44 -07001664status_t MediaPlayerService::AudioOutput::getTimestamp(AudioTimestamp &ts) const
1665{
Andy Hungd1c74342015-07-07 16:54:23 -07001666 Mutex::Autolock lock(mLock);
Lajos Molnar06ad1522014-08-28 07:27:44 -07001667 if (mTrack == 0) return NO_INIT;
1668 return mTrack->getTimestamp(ts);
1669}
1670
Wei Jiac4ac8172015-10-21 10:35:48 -07001671// TODO: Remove unnecessary calls to getPlayedOutDurationUs()
1672// as it acquires locks and may query the audio driver.
1673//
1674// Some calls could conceivably retrieve extrapolated data instead of
1675// accessing getTimestamp() or getPosition() every time a data buffer with
1676// a media time is received.
1677//
1678// Calculate duration of played samples if played at normal rate (i.e., 1.0).
1679int64_t MediaPlayerService::AudioOutput::getPlayedOutDurationUs(int64_t nowUs) const
1680{
1681 Mutex::Autolock lock(mLock);
1682 if (mTrack == 0 || mSampleRateHz == 0) {
Wei Jia213f4902015-10-22 08:55:25 -07001683 return 0;
Wei Jiac4ac8172015-10-21 10:35:48 -07001684 }
1685
1686 uint32_t numFramesPlayed;
Andy Hung5d313802016-10-10 15:09:39 -07001687 int64_t numFramesPlayedAtUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001688 AudioTimestamp ts;
Wei Jiac4ac8172015-10-21 10:35:48 -07001689
1690 status_t res = mTrack->getTimestamp(ts);
1691 if (res == OK) { // case 1: mixing audio tracks and offloaded tracks.
1692 numFramesPlayed = ts.mPosition;
Andy Hung5d313802016-10-10 15:09:39 -07001693 numFramesPlayedAtUs = ts.mTime.tv_sec * 1000000LL + ts.mTime.tv_nsec / 1000;
1694 //ALOGD("getTimestamp: OK %d %lld", numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001695 } else if (res == WOULD_BLOCK) { // case 2: transitory state on start of a new track
1696 numFramesPlayed = 0;
Andy Hung5d313802016-10-10 15:09:39 -07001697 numFramesPlayedAtUs = nowUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001698 //ALOGD("getTimestamp: WOULD_BLOCK %d %lld",
Andy Hung5d313802016-10-10 15:09:39 -07001699 // numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001700 } else { // case 3: transitory at new track or audio fast tracks.
1701 res = mTrack->getPosition(&numFramesPlayed);
1702 CHECK_EQ(res, (status_t)OK);
Andy Hung5d313802016-10-10 15:09:39 -07001703 numFramesPlayedAtUs = nowUs;
1704 numFramesPlayedAtUs += 1000LL * mTrack->latency() / 2; /* XXX */
1705 //ALOGD("getPosition: %u %lld", numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001706 }
1707
1708 // CHECK_EQ(numFramesPlayed & (1 << 31), 0); // can't be negative until 12.4 hrs, test
1709 // TODO: remove the (int32_t) casting below as it may overflow at 12.4 hours.
1710 int64_t durationUs = (int64_t)((int32_t)numFramesPlayed * 1000000LL / mSampleRateHz)
Andy Hung5d313802016-10-10 15:09:39 -07001711 + nowUs - numFramesPlayedAtUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001712 if (durationUs < 0) {
1713 // Occurs when numFramesPlayed position is very small and the following:
1714 // (1) In case 1, the time nowUs is computed before getTimestamp() is called and
Andy Hung5d313802016-10-10 15:09:39 -07001715 // numFramesPlayedAtUs is greater than nowUs by time more than numFramesPlayed.
Wei Jiac4ac8172015-10-21 10:35:48 -07001716 // (2) In case 3, using getPosition and adding mAudioSink->latency() to
Andy Hung5d313802016-10-10 15:09:39 -07001717 // numFramesPlayedAtUs, by a time amount greater than numFramesPlayed.
Wei Jiac4ac8172015-10-21 10:35:48 -07001718 //
1719 // Both of these are transitory conditions.
1720 ALOGV("getPlayedOutDurationUs: negative duration %lld set to zero", (long long)durationUs);
1721 durationUs = 0;
1722 }
1723 ALOGV("getPlayedOutDurationUs(%lld) nowUs(%lld) frames(%u) framesAt(%lld)",
Andy Hung5d313802016-10-10 15:09:39 -07001724 (long long)durationUs, (long long)nowUs,
1725 numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001726 return durationUs;
1727}
1728
Marco Nelissen4110c102012-03-29 09:31:28 -07001729status_t MediaPlayerService::AudioOutput::getFramesWritten(uint32_t *frameswritten) const
1730{
Andy Hungd1c74342015-07-07 16:54:23 -07001731 Mutex::Autolock lock(mLock);
Marco Nelissen4110c102012-03-29 09:31:28 -07001732 if (mTrack == 0) return NO_INIT;
Andy Hung2f6e73d2016-04-08 12:12:58 -07001733 ExtendedTimestamp ets;
1734 status_t status = mTrack->getTimestamp(&ets);
1735 if (status == OK || status == WOULD_BLOCK) {
1736 *frameswritten = (uint32_t)ets.mPosition[ExtendedTimestamp::LOCATION_CLIENT];
1737 }
1738 return status;
Marco Nelissen4110c102012-03-29 09:31:28 -07001739}
1740
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001741status_t MediaPlayerService::AudioOutput::setParameters(const String8& keyValuePairs)
1742{
Andy Hungd1c74342015-07-07 16:54:23 -07001743 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001744 if (mTrack == 0) return NO_INIT;
1745 return mTrack->setParameters(keyValuePairs);
1746}
1747
1748String8 MediaPlayerService::AudioOutput::getParameters(const String8& keys)
1749{
Andy Hungd1c74342015-07-07 16:54:23 -07001750 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001751 if (mTrack == 0) return String8::empty();
1752 return mTrack->getParameters(keys);
1753}
1754
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001755void MediaPlayerService::AudioOutput::setAudioAttributes(const audio_attributes_t * attributes) {
Andy Hungd1c74342015-07-07 16:54:23 -07001756 Mutex::Autolock lock(mLock);
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001757 if (attributes == NULL) {
1758 free(mAttributes);
1759 mAttributes = NULL;
1760 } else {
1761 if (mAttributes == NULL) {
1762 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1763 }
1764 memcpy(mAttributes, attributes, sizeof(audio_attributes_t));
Eric Laurent43562692015-07-15 16:49:07 -07001765 mStreamType = audio_attributes_to_stream_type(attributes);
1766 }
1767}
1768
1769void MediaPlayerService::AudioOutput::setAudioStreamType(audio_stream_type_t streamType)
1770{
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001771 Mutex::Autolock lock(mLock);
Eric Laurent43562692015-07-15 16:49:07 -07001772 // do not allow direct stream type modification if attributes have been set
1773 if (mAttributes == NULL) {
1774 mStreamType = streamType;
1775 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001776}
1777
Andy Hungd1c74342015-07-07 16:54:23 -07001778void MediaPlayerService::AudioOutput::deleteRecycledTrack_l()
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001779{
Andy Hungd1c74342015-07-07 16:54:23 -07001780 ALOGV("deleteRecycledTrack_l");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001781 if (mRecycledTrack != 0) {
1782
1783 if (mCallbackData != NULL) {
1784 mCallbackData->setOutput(NULL);
1785 mCallbackData->endTrackSwitch();
1786 }
1787
1788 if ((mRecycledTrack->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) {
Andy Hunge13f8a62016-03-30 14:20:42 -07001789 int32_t msec = 0;
1790 if (!mRecycledTrack->stopped()) { // check if active
1791 (void)mRecycledTrack->pendingDuration(&msec);
1792 }
1793 mRecycledTrack->stop(); // ensure full data drain
1794 ALOGD("deleting recycled track, waiting for data drain (%d msec)", msec);
1795 if (msec > 0) {
1796 static const int32_t WAIT_LIMIT_MS = 3000;
1797 if (msec > WAIT_LIMIT_MS) {
1798 msec = WAIT_LIMIT_MS;
1799 }
1800 usleep(msec * 1000LL);
1801 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001802 }
1803 // An offloaded track isn't flushed because the STREAM_END is reported
1804 // slightly prematurely to allow time for the gapless track switch
1805 // but this means that if we decide not to recycle the track there
1806 // could be a small amount of residual data still playing. We leave
1807 // AudioFlinger to drain the track.
1808
1809 mRecycledTrack.clear();
Andy Hungd1c74342015-07-07 16:54:23 -07001810 close_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001811 delete mCallbackData;
1812 mCallbackData = NULL;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001813 }
1814}
1815
Andy Hungd1c74342015-07-07 16:54:23 -07001816void MediaPlayerService::AudioOutput::close_l()
1817{
1818 mTrack.clear();
1819}
1820
Andreas Huber20111aa2009-07-14 16:56:47 -07001821status_t MediaPlayerService::AudioOutput::open(
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001822 uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
1823 audio_format_t format, int bufferCount,
Eric Laurent1948eb32012-04-13 16:50:19 -07001824 AudioCallback cb, void *cookie,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001825 audio_output_flags_t flags,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001826 const audio_offload_info_t *offloadInfo,
Andy Hung179652e2015-05-31 22:49:46 -07001827 bool doNotReconnect,
1828 uint32_t suggestedFrameCount)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001829{
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001830 ALOGV("open(%u, %d, 0x%x, 0x%x, %d, %d 0x%x)", sampleRate, channelCount, channelMask,
1831 format, bufferCount, mSessionId, flags);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001832
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001833 // offloading is only supported in callback mode for now.
1834 // offloadInfo must be present if offload flag is set
1835 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) &&
1836 ((cb == NULL) || (offloadInfo == NULL))) {
1837 return BAD_VALUE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001838 }
1839
Andy Hung179652e2015-05-31 22:49:46 -07001840 // compute frame count for the AudioTrack internal buffer
1841 size_t frameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001842 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1843 frameCount = 0; // AudioTrack will get frame count from AudioFlinger
1844 } else {
Andy Hung179652e2015-05-31 22:49:46 -07001845 // try to estimate the buffer processing fetch size from AudioFlinger.
1846 // framesPerBuffer is approximate and generally correct, except when it's not :-).
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001847 uint32_t afSampleRate;
1848 size_t afFrameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001849 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1850 return NO_INIT;
1851 }
1852 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1853 return NO_INIT;
1854 }
Andy Hung179652e2015-05-31 22:49:46 -07001855 const size_t framesPerBuffer =
1856 (unsigned long long)sampleRate * afFrameCount / afSampleRate;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001857
Andy Hung179652e2015-05-31 22:49:46 -07001858 if (bufferCount == 0) {
1859 // use suggestedFrameCount
1860 bufferCount = (suggestedFrameCount + framesPerBuffer - 1) / framesPerBuffer;
1861 }
1862 // Check argument bufferCount against the mininum buffer count
1863 if (bufferCount != 0 && bufferCount < mMinBufferCount) {
1864 ALOGV("bufferCount (%d) increased to %d", bufferCount, mMinBufferCount);
1865 bufferCount = mMinBufferCount;
1866 }
1867 // if frameCount is 0, then AudioTrack will get frame count from AudioFlinger
1868 // which will be the minimum size permitted.
1869 frameCount = bufferCount * framesPerBuffer;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001870 }
Andreas Huber20111aa2009-07-14 16:56:47 -07001871
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001872 if (channelMask == CHANNEL_MASK_USE_CHANNEL_ORDER) {
Glenn Kastenab334fd2012-03-14 12:56:06 -07001873 channelMask = audio_channel_out_mask_from_count(channelCount);
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001874 if (0 == channelMask) {
1875 ALOGE("open() error, can\'t derive mask for %d audio channels", channelCount);
1876 return NO_INIT;
1877 }
1878 }
Eric Laurent1948eb32012-04-13 16:50:19 -07001879
Andy Hungd1c74342015-07-07 16:54:23 -07001880 Mutex::Autolock lock(mLock);
Andy Hung179652e2015-05-31 22:49:46 -07001881 mCallback = cb;
1882 mCallbackCookie = cookie;
1883
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001884 // Check whether we can recycle the track
1885 bool reuse = false;
1886 bool bothOffloaded = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001887
Glenn Kasten2799d742013-05-30 14:33:29 -07001888 if (mRecycledTrack != 0) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001889 // check whether we are switching between two offloaded tracks
1890 bothOffloaded = (flags & mRecycledTrack->getFlags()
1891 & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0;
Marco Nelissen67295b52012-06-11 14:52:53 -07001892
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001893 // check if the existing track can be reused as-is, or if a new track needs to be created.
1894 reuse = true;
1895
Marco Nelissen67295b52012-06-11 14:52:53 -07001896 if ((mCallbackData == NULL && mCallback != NULL) ||
1897 (mCallbackData != NULL && mCallback == NULL)) {
1898 // recycled track uses callbacks but the caller wants to use writes, or vice versa
1899 ALOGV("can't chain callback and write");
1900 reuse = false;
1901 } else if ((mRecycledTrack->getSampleRate() != sampleRate) ||
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001902 (mRecycledTrack->channelCount() != (uint32_t)channelCount) ) {
1903 ALOGV("samplerate, channelcount differ: %u/%u Hz, %u/%d ch",
Marco Nelissen67295b52012-06-11 14:52:53 -07001904 mRecycledTrack->getSampleRate(), sampleRate,
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001905 mRecycledTrack->channelCount(), channelCount);
Marco Nelissen67295b52012-06-11 14:52:53 -07001906 reuse = false;
1907 } else if (flags != mFlags) {
1908 ALOGV("output flags differ %08x/%08x", flags, mFlags);
1909 reuse = false;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001910 } else if (mRecycledTrack->format() != format) {
1911 reuse = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001912 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001913 } else {
1914 ALOGV("no track available to recycle");
1915 }
1916
1917 ALOGV_IF(bothOffloaded, "both tracks offloaded");
1918
1919 // If we can't recycle and both tracks are offloaded
1920 // we must close the previous output before opening a new one
1921 if (bothOffloaded && !reuse) {
1922 ALOGV("both offloaded and not recycling");
Andy Hungd1c74342015-07-07 16:54:23 -07001923 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001924 }
1925
1926 sp<AudioTrack> t;
1927 CallbackData *newcbd = NULL;
1928
1929 // We don't attempt to create a new track if we are recycling an
1930 // offloaded track. But, if we are recycling a non-offloaded or we
1931 // are switching where one is offloaded and one isn't then we create
1932 // the new track in advance so that we can read additional stream info
1933
1934 if (!(reuse && bothOffloaded)) {
1935 ALOGV("creating new AudioTrack");
1936
1937 if (mCallback != NULL) {
1938 newcbd = new CallbackData(this);
1939 t = new AudioTrack(
1940 mStreamType,
1941 sampleRate,
1942 format,
1943 channelMask,
1944 frameCount,
1945 flags,
1946 CallbackWrapper,
1947 newcbd,
1948 0, // notification frames
1949 mSessionId,
1950 AudioTrack::TRANSFER_CALLBACK,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001951 offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -08001952 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001953 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001954 mAttributes,
1955 doNotReconnect);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001956 } else {
Andy Hungff874dc2016-04-11 16:49:09 -07001957 // TODO: Due to buffer memory concerns, we use a max target playback speed
1958 // based on mPlaybackRate at the time of open (instead of kMaxRequiredSpeed),
1959 // also clamping the target speed to 1.0 <= targetSpeed <= kMaxRequiredSpeed.
1960 const float targetSpeed =
1961 std::min(std::max(mPlaybackRate.mSpeed, 1.0f), kMaxRequiredSpeed);
1962 ALOGW_IF(targetSpeed != mPlaybackRate.mSpeed,
1963 "track target speed:%f clamped from playback speed:%f",
1964 targetSpeed, mPlaybackRate.mSpeed);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001965 t = new AudioTrack(
1966 mStreamType,
1967 sampleRate,
1968 format,
1969 channelMask,
1970 frameCount,
1971 flags,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001972 NULL, // callback
1973 NULL, // user data
1974 0, // notification frames
1975 mSessionId,
1976 AudioTrack::TRANSFER_DEFAULT,
1977 NULL, // offload info
Marco Nelissend457c972014-02-11 08:47:07 -08001978 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001979 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001980 mAttributes,
Andy Hungff874dc2016-04-11 16:49:09 -07001981 doNotReconnect,
1982 targetSpeed);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001983 }
1984
1985 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1986 ALOGE("Unable to create audio track");
1987 delete newcbd;
Glenn Kasten3e98ecd2015-05-18 13:13:24 -07001988 // t goes out of scope, so reference count drops to zero
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001989 return NO_INIT;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001990 } else {
1991 // successful AudioTrack initialization implies a legacy stream type was generated
1992 // from the audio attributes
1993 mStreamType = t->streamType();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001994 }
1995 }
1996
1997 if (reuse) {
1998 CHECK(mRecycledTrack != NULL);
1999
2000 if (!bothOffloaded) {
2001 if (mRecycledTrack->frameCount() != t->frameCount()) {
Andy Hung833b4752016-04-04 17:15:48 -07002002 ALOGV("framecount differs: %zu/%zu frames",
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002003 mRecycledTrack->frameCount(), t->frameCount());
2004 reuse = false;
2005 }
2006 }
2007
Marco Nelissen67295b52012-06-11 14:52:53 -07002008 if (reuse) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002009 ALOGV("chaining to next output and recycling track");
Andy Hungd1c74342015-07-07 16:54:23 -07002010 close_l();
Marco Nelissen67295b52012-06-11 14:52:53 -07002011 mTrack = mRecycledTrack;
Glenn Kasten2799d742013-05-30 14:33:29 -07002012 mRecycledTrack.clear();
Marco Nelissen67295b52012-06-11 14:52:53 -07002013 if (mCallbackData != NULL) {
2014 mCallbackData->setOutput(this);
2015 }
Marco Nelissen67295b52012-06-11 14:52:53 -07002016 delete newcbd;
Wei Jiae0bbac92016-07-18 16:04:53 -07002017 return updateTrack();
Marco Nelissen67295b52012-06-11 14:52:53 -07002018 }
Marco Nelissen67295b52012-06-11 14:52:53 -07002019 }
2020
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002021 // we're not going to reuse the track, unblock and flush it
2022 // this was done earlier if both tracks are offloaded
2023 if (!bothOffloaded) {
Andy Hungd1c74342015-07-07 16:54:23 -07002024 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002025 }
2026
2027 CHECK((t != NULL) && ((mCallback == NULL) || (newcbd != NULL)));
2028
Marco Nelissen67295b52012-06-11 14:52:53 -07002029 mCallbackData = newcbd;
Steve Block3856b092011-10-20 11:56:00 +01002030 ALOGV("setVolume");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002031 t->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07002032
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002033 mSampleRateHz = sampleRate;
Preetam Singh Ranawat2e17eef2015-08-12 12:11:46 -07002034 mFlags = flags;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002035 mMsecsPerFrame = 1E3f / (mPlaybackRate.mSpeed * sampleRate);
Andy Hungd1c74342015-07-07 16:54:23 -07002036 mFrameSize = t->frameSize();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002037 mTrack = t;
Eric Laurent2beeb502010-07-16 07:43:46 -07002038
Wei Jiae0bbac92016-07-18 16:04:53 -07002039 return updateTrack();
2040}
2041
2042status_t MediaPlayerService::AudioOutput::updateTrack() {
2043 if (mTrack == NULL) {
2044 return NO_ERROR;
2045 }
2046
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002047 status_t res = NO_ERROR;
Wei Jia0162d002015-06-09 11:59:33 -07002048 // Note some output devices may give us a direct track even though we don't specify it.
2049 // Example: Line application b/17459982.
Wei Jiae0bbac92016-07-18 16:04:53 -07002050 if ((mTrack->getFlags()
2051 & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) {
2052 res = mTrack->setPlaybackRate(mPlaybackRate);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002053 if (res == NO_ERROR) {
Wei Jiae0bbac92016-07-18 16:04:53 -07002054 mTrack->setAuxEffectSendLevel(mSendLevel);
2055 res = mTrack->attachAuxEffect(mAuxEffectId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002056 }
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002057 }
Wei Jiae0bbac92016-07-18 16:04:53 -07002058 ALOGV("updateTrack() DONE status %d", res);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002059 return res;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002060}
2061
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002062status_t MediaPlayerService::AudioOutput::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002063{
Steve Block3856b092011-10-20 11:56:00 +01002064 ALOGV("start");
Andy Hungd1c74342015-07-07 16:54:23 -07002065 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08002066 if (mCallbackData != NULL) {
2067 mCallbackData->endTrackSwitch();
2068 }
Glenn Kasten2799d742013-05-30 14:33:29 -07002069 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002070 mTrack->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07002071 mTrack->setAuxEffectSendLevel(mSendLevel);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002072 return mTrack->start();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002073 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002074 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002075}
2076
Marco Nelissen6b74d672012-02-28 16:07:44 -08002077void MediaPlayerService::AudioOutput::setNextOutput(const sp<AudioOutput>& nextOutput) {
Andy Hungd1c74342015-07-07 16:54:23 -07002078 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08002079 mNextOutput = nextOutput;
2080}
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08002081
Marco Nelissen6b74d672012-02-28 16:07:44 -08002082void MediaPlayerService::AudioOutput::switchToNextOutput() {
2083 ALOGV("switchToNextOutput");
Andy Hungd1c74342015-07-07 16:54:23 -07002084
2085 // Try to acquire the callback lock before moving track (without incurring deadlock).
2086 const unsigned kMaxSwitchTries = 100;
2087 Mutex::Autolock lock(mLock);
2088 for (unsigned tries = 0;;) {
2089 if (mTrack == 0) {
2090 return;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002091 }
Andy Hungd1c74342015-07-07 16:54:23 -07002092 if (mNextOutput != NULL && mNextOutput != this) {
2093 if (mCallbackData != NULL) {
2094 // two alternative approaches
2095#if 1
2096 CallbackData *callbackData = mCallbackData;
2097 mLock.unlock();
2098 // proper acquisition sequence
2099 callbackData->lock();
2100 mLock.lock();
2101 // Caution: it is unlikely that someone deleted our callback or changed our target
2102 if (callbackData != mCallbackData || mNextOutput == NULL || mNextOutput == this) {
2103 // fatal if we are starved out.
2104 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
2105 "switchToNextOutput() cannot obtain correct lock sequence");
2106 callbackData->unlock();
2107 continue;
2108 }
2109 callbackData->mSwitching = true; // begin track switch
Wei Jiaadee56a2016-08-05 15:40:34 -07002110 callbackData->setOutput(NULL);
Andy Hungd1c74342015-07-07 16:54:23 -07002111#else
2112 // tryBeginTrackSwitch() returns false if the callback has the lock.
2113 if (!mCallbackData->tryBeginTrackSwitch()) {
2114 // fatal if we are starved out.
2115 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
2116 "switchToNextOutput() cannot obtain callback lock");
2117 mLock.unlock();
2118 usleep(5 * 1000 /* usec */); // allow callback to use AudioOutput
2119 mLock.lock();
2120 continue;
2121 }
2122#endif
2123 }
2124
2125 Mutex::Autolock nextLock(mNextOutput->mLock);
2126
2127 // If the next output track is not NULL, then it has been
2128 // opened already for playback.
2129 // This is possible even without the next player being started,
2130 // for example, the next player could be prepared and seeked.
2131 //
2132 // Presuming it isn't advisable to force the track over.
2133 if (mNextOutput->mTrack == NULL) {
2134 ALOGD("Recycling track for gapless playback");
2135 delete mNextOutput->mCallbackData;
2136 mNextOutput->mCallbackData = mCallbackData;
2137 mNextOutput->mRecycledTrack = mTrack;
2138 mNextOutput->mSampleRateHz = mSampleRateHz;
2139 mNextOutput->mMsecsPerFrame = mMsecsPerFrame;
Andy Hungd1c74342015-07-07 16:54:23 -07002140 mNextOutput->mFlags = mFlags;
2141 mNextOutput->mFrameSize = mFrameSize;
2142 close_l();
2143 mCallbackData = NULL; // destruction handled by mNextOutput
2144 } else {
2145 ALOGW("Ignoring gapless playback because next player has already started");
2146 // remove track in case resource needed for future players.
2147 if (mCallbackData != NULL) {
2148 mCallbackData->endTrackSwitch(); // release lock for callbacks before close.
2149 }
2150 close_l();
2151 }
2152 }
2153 break;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002154 }
2155}
2156
Wei Jia7d3f4df2015-03-03 15:28:00 -08002157ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002158{
Andy Hungd1c74342015-07-07 16:54:23 -07002159 Mutex::Autolock lock(mLock);
Glenn Kastenadad3d72014-02-21 14:51:43 -08002160 LOG_ALWAYS_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
Andreas Huber20111aa2009-07-14 16:56:47 -07002161
Steve Block3856b092011-10-20 11:56:00 +01002162 //ALOGV("write(%p, %u)", buffer, size);
Glenn Kasten2799d742013-05-30 14:33:29 -07002163 if (mTrack != 0) {
Andy Hung2f6e73d2016-04-08 12:12:58 -07002164 return mTrack->write(buffer, size, blocking);
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07002165 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002166 return NO_INIT;
2167}
2168
2169void MediaPlayerService::AudioOutput::stop()
2170{
Steve Block3856b092011-10-20 11:56:00 +01002171 ALOGV("stop");
Andy Hungd1c74342015-07-07 16:54:23 -07002172 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002173 if (mTrack != 0) mTrack->stop();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002174}
2175
2176void MediaPlayerService::AudioOutput::flush()
2177{
Steve Block3856b092011-10-20 11:56:00 +01002178 ALOGV("flush");
Andy Hungd1c74342015-07-07 16:54:23 -07002179 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002180 if (mTrack != 0) mTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002181}
2182
2183void MediaPlayerService::AudioOutput::pause()
2184{
Steve Block3856b092011-10-20 11:56:00 +01002185 ALOGV("pause");
Andy Hungd1c74342015-07-07 16:54:23 -07002186 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002187 if (mTrack != 0) mTrack->pause();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002188}
2189
2190void MediaPlayerService::AudioOutput::close()
2191{
Steve Block3856b092011-10-20 11:56:00 +01002192 ALOGV("close");
Erik Wolsheimer7845a1f2015-10-30 12:07:52 -07002193 sp<AudioTrack> track;
2194 {
2195 Mutex::Autolock lock(mLock);
2196 track = mTrack;
2197 close_l(); // clears mTrack
2198 }
2199 // destruction of the track occurs outside of mutex.
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002200}
2201
2202void MediaPlayerService::AudioOutput::setVolume(float left, float right)
2203{
Steve Block3856b092011-10-20 11:56:00 +01002204 ALOGV("setVolume(%f, %f)", left, right);
Andy Hungd1c74342015-07-07 16:54:23 -07002205 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002206 mLeftVolume = left;
2207 mRightVolume = right;
Glenn Kasten2799d742013-05-30 14:33:29 -07002208 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002209 mTrack->setVolume(left, right);
2210 }
2211}
2212
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002213status_t MediaPlayerService::AudioOutput::setPlaybackRate(const AudioPlaybackRate &rate)
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002214{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002215 ALOGV("setPlaybackRate(%f %f %d %d)",
2216 rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Andy Hungd1c74342015-07-07 16:54:23 -07002217 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002218 if (mTrack == 0) {
2219 // remember rate so that we can set it when the track is opened
2220 mPlaybackRate = rate;
2221 return OK;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002222 }
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002223 status_t res = mTrack->setPlaybackRate(rate);
2224 if (res != NO_ERROR) {
2225 return res;
2226 }
2227 // rate.mSpeed is always greater than 0 if setPlaybackRate succeeded
2228 CHECK_GT(rate.mSpeed, 0.f);
2229 mPlaybackRate = rate;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002230 if (mSampleRateHz != 0) {
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002231 mMsecsPerFrame = 1E3f / (rate.mSpeed * mSampleRateHz);
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002232 }
2233 return res;
2234}
2235
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002236status_t MediaPlayerService::AudioOutput::getPlaybackRate(AudioPlaybackRate *rate)
2237{
2238 ALOGV("setPlaybackRate");
Andy Hungd1c74342015-07-07 16:54:23 -07002239 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002240 if (mTrack == 0) {
2241 return NO_INIT;
2242 }
2243 *rate = mTrack->getPlaybackRate();
2244 return NO_ERROR;
2245}
2246
Eric Laurent2beeb502010-07-16 07:43:46 -07002247status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
2248{
Steve Block3856b092011-10-20 11:56:00 +01002249 ALOGV("setAuxEffectSendLevel(%f)", level);
Andy Hungd1c74342015-07-07 16:54:23 -07002250 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002251 mSendLevel = level;
Glenn Kasten2799d742013-05-30 14:33:29 -07002252 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002253 return mTrack->setAuxEffectSendLevel(level);
2254 }
2255 return NO_ERROR;
2256}
2257
2258status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
2259{
Steve Block3856b092011-10-20 11:56:00 +01002260 ALOGV("attachAuxEffect(%d)", effectId);
Andy Hungd1c74342015-07-07 16:54:23 -07002261 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002262 mAuxEffectId = effectId;
Glenn Kasten2799d742013-05-30 14:33:29 -07002263 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002264 return mTrack->attachAuxEffect(effectId);
2265 }
2266 return NO_ERROR;
2267}
2268
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002269VolumeShaper::Status MediaPlayerService::AudioOutput::applyVolumeShaper(
2270 const sp<VolumeShaper::Configuration>& configuration,
2271 const sp<VolumeShaper::Operation>& operation)
2272{
2273 Mutex::Autolock lock(mLock);
2274 ALOGV("AudioOutput::applyVolumeShaper");
2275 if (mTrack != 0) {
2276 return mTrack->applyVolumeShaper(configuration, operation);
2277 }
2278 return VolumeShaper::Status(INVALID_OPERATION);
2279}
2280
2281sp<VolumeShaper::State> MediaPlayerService::AudioOutput::getVolumeShaperState(int id)
2282{
2283 Mutex::Autolock lock(mLock);
2284 if (mTrack != 0) {
2285 return mTrack->getVolumeShaperState(id);
2286 }
2287 return nullptr;
2288}
2289
Andreas Huber20111aa2009-07-14 16:56:47 -07002290// static
2291void MediaPlayerService::AudioOutput::CallbackWrapper(
Glenn Kastend217a8c2011-06-01 15:20:35 -07002292 int event, void *cookie, void *info) {
Steve Block3856b092011-10-20 11:56:00 +01002293 //ALOGV("callbackwrapper");
Marco Nelissen6b74d672012-02-28 16:07:44 -08002294 CallbackData *data = (CallbackData*)cookie;
Andy Hungd1c74342015-07-07 16:54:23 -07002295 // lock to ensure we aren't caught in the middle of a track switch.
Marco Nelissen6b74d672012-02-28 16:07:44 -08002296 data->lock();
2297 AudioOutput *me = data->getOutput();
Andreas Huber20111aa2009-07-14 16:56:47 -07002298 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002299 if (me == NULL) {
2300 // no output set, likely because the track was scheduled to be reused
2301 // by another player, but the format turned out to be incompatible.
2302 data->unlock();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002303 if (buffer != NULL) {
2304 buffer->size = 0;
2305 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08002306 return;
2307 }
Andreas Huber20111aa2009-07-14 16:56:47 -07002308
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002309 switch(event) {
2310 case AudioTrack::EVENT_MORE_DATA: {
2311 size_t actualSize = (*me->mCallback)(
2312 me, buffer->raw, buffer->size, me->mCallbackCookie,
2313 CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002314
Andy Hung719b46b2015-05-31 22:18:25 -07002315 // Log when no data is returned from the callback.
2316 // (1) We may have no data (especially with network streaming sources).
2317 // (2) We may have reached the EOS and the audio track is not stopped yet.
2318 // Note that AwesomePlayer/AudioPlayer will only return zero size when it reaches the EOS.
2319 // NuPlayerRenderer will return zero when it doesn't have data (it doesn't block to fill).
2320 //
2321 // This is a benign busy-wait, with the next data request generated 10 ms or more later;
2322 // nevertheless for power reasons, we don't want to see too many of these.
Andreas Huber2e8ffaf2010-02-18 16:45:13 -08002323
Andy Hung719b46b2015-05-31 22:18:25 -07002324 ALOGV_IF(actualSize == 0 && buffer->size > 0, "callbackwrapper: empty buffer returned");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002325
2326 buffer->size = actualSize;
2327 } break;
2328
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002329 case AudioTrack::EVENT_STREAM_END:
Andy Hung719b46b2015-05-31 22:18:25 -07002330 // currently only occurs for offloaded callbacks
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002331 ALOGV("callbackwrapper: deliver EVENT_STREAM_END");
2332 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2333 me->mCallbackCookie, CB_EVENT_STREAM_END);
2334 break;
2335
2336 case AudioTrack::EVENT_NEW_IAUDIOTRACK :
2337 ALOGV("callbackwrapper: deliver EVENT_TEAR_DOWN");
2338 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2339 me->mCallbackCookie, CB_EVENT_TEAR_DOWN);
2340 break;
2341
Glenn Kasten421743b2015-06-01 08:18:08 -07002342 case AudioTrack::EVENT_UNDERRUN:
Andy Hung719b46b2015-05-31 22:18:25 -07002343 // This occurs when there is no data available, typically
Glenn Kasten421743b2015-06-01 08:18:08 -07002344 // when there is a failure to supply data to the AudioTrack. It can also
2345 // occur in non-offloaded mode when the audio device comes out of standby.
2346 //
Andy Hung719b46b2015-05-31 22:18:25 -07002347 // If an AudioTrack underruns it outputs silence. Since this happens suddenly
2348 // it may sound like an audible pop or glitch.
2349 //
2350 // The underrun event is sent once per track underrun; the condition is reset
2351 // when more data is sent to the AudioTrack.
Eric Laurente93cc032016-05-05 10:15:10 -07002352 ALOGD("callbackwrapper: EVENT_UNDERRUN (discarded)");
Glenn Kasten421743b2015-06-01 08:18:08 -07002353 break;
2354
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002355 default:
2356 ALOGE("received unknown event type: %d inside CallbackWrapper !", event);
Andreas Huber51c1e0e2011-04-04 11:43:40 -07002357 }
2358
Marco Nelissen6b74d672012-02-28 16:07:44 -08002359 data->unlock();
Andreas Huber20111aa2009-07-14 16:56:47 -07002360}
2361
Glenn Kastend848eb42016-03-08 13:42:11 -08002362audio_session_t MediaPlayerService::AudioOutput::getSessionId() const
Eric Laurent8c563ed2010-10-07 18:23:03 -07002363{
Andy Hungd1c74342015-07-07 16:54:23 -07002364 Mutex::Autolock lock(mLock);
Eric Laurent8c563ed2010-10-07 18:23:03 -07002365 return mSessionId;
2366}
2367
Eric Laurent6f59db12013-07-26 17:16:50 -07002368uint32_t MediaPlayerService::AudioOutput::getSampleRate() const
2369{
Andy Hungd1c74342015-07-07 16:54:23 -07002370 Mutex::Autolock lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -07002371 if (mTrack == 0) return 0;
2372 return mTrack->getSampleRate();
2373}
2374
Andy Hungf2c87b32016-04-07 19:49:29 -07002375int64_t MediaPlayerService::AudioOutput::getBufferDurationInUs() const
2376{
2377 Mutex::Autolock lock(mLock);
2378 if (mTrack == 0) {
2379 return 0;
2380 }
2381 int64_t duration;
2382 if (mTrack->getBufferDurationInUs(&duration) != OK) {
2383 return 0;
2384 }
2385 return duration;
2386}
2387
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002388////////////////////////////////////////////////////////////////////////////////
2389
2390struct CallbackThread : public Thread {
2391 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
2392 MediaPlayerBase::AudioSink::AudioCallback cb,
2393 void *cookie);
2394
2395protected:
2396 virtual ~CallbackThread();
2397
2398 virtual bool threadLoop();
2399
2400private:
2401 wp<MediaPlayerBase::AudioSink> mSink;
2402 MediaPlayerBase::AudioSink::AudioCallback mCallback;
2403 void *mCookie;
2404 void *mBuffer;
2405 size_t mBufferSize;
2406
2407 CallbackThread(const CallbackThread &);
2408 CallbackThread &operator=(const CallbackThread &);
2409};
2410
2411CallbackThread::CallbackThread(
2412 const wp<MediaPlayerBase::AudioSink> &sink,
2413 MediaPlayerBase::AudioSink::AudioCallback cb,
2414 void *cookie)
2415 : mSink(sink),
2416 mCallback(cb),
2417 mCookie(cookie),
2418 mBuffer(NULL),
2419 mBufferSize(0) {
2420}
2421
2422CallbackThread::~CallbackThread() {
2423 if (mBuffer) {
2424 free(mBuffer);
2425 mBuffer = NULL;
2426 }
2427}
2428
2429bool CallbackThread::threadLoop() {
2430 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
2431 if (sink == NULL) {
2432 return false;
2433 }
2434
2435 if (mBuffer == NULL) {
2436 mBufferSize = sink->bufferSize();
2437 mBuffer = malloc(mBufferSize);
2438 }
2439
2440 size_t actualSize =
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002441 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie,
2442 MediaPlayerBase::AudioSink::CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002443
2444 if (actualSize > 0) {
2445 sink->write(mBuffer, actualSize);
Andy Hunga31335a2014-08-20 17:37:59 -07002446 // Could return false on sink->write() error or short count.
2447 // Not necessarily appropriate but would work for AudioCache behavior.
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002448 }
2449
2450 return true;
2451}
2452
2453////////////////////////////////////////////////////////////////////////////////
2454
Gloria Wang7cf180c2011-02-19 18:37:57 -08002455void MediaPlayerService::addBatteryData(uint32_t params)
2456{
2457 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002458
2459 int32_t time = systemTime() / 1000000L;
2460
2461 // change audio output devices. This notification comes from AudioFlinger
2462 if ((params & kBatteryDataSpeakerOn)
2463 || (params & kBatteryDataOtherAudioDeviceOn)) {
2464
2465 int deviceOn[NUM_AUDIO_DEVICES];
2466 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2467 deviceOn[i] = 0;
2468 }
2469
2470 if ((params & kBatteryDataSpeakerOn)
2471 && (params & kBatteryDataOtherAudioDeviceOn)) {
2472 deviceOn[SPEAKER_AND_OTHER] = 1;
2473 } else if (params & kBatteryDataSpeakerOn) {
2474 deviceOn[SPEAKER] = 1;
2475 } else {
2476 deviceOn[OTHER_AUDIO_DEVICE] = 1;
2477 }
2478
2479 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2480 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
2481
2482 if (mBatteryAudio.refCount > 0) { // if playing audio
2483 if (!deviceOn[i]) {
2484 mBatteryAudio.lastTime[i] += time;
2485 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2486 mBatteryAudio.lastTime[i] = 0;
2487 } else {
2488 mBatteryAudio.lastTime[i] = 0 - time;
2489 }
2490 }
2491
2492 mBatteryAudio.deviceOn[i] = deviceOn[i];
2493 }
2494 }
2495 return;
2496 }
2497
Marco Nelissenb7848f12014-12-04 08:57:56 -08002498 // an audio stream is started
Gloria Wang9ee159b2011-02-24 14:51:45 -08002499 if (params & kBatteryDataAudioFlingerStart) {
2500 // record the start time only if currently no other audio
2501 // is being played
2502 if (mBatteryAudio.refCount == 0) {
2503 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2504 if (mBatteryAudio.deviceOn[i]) {
2505 mBatteryAudio.lastTime[i] -= time;
2506 }
2507 }
2508 }
2509
2510 mBatteryAudio.refCount ++;
2511 return;
2512
2513 } else if (params & kBatteryDataAudioFlingerStop) {
2514 if (mBatteryAudio.refCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002515 ALOGW("Battery track warning: refCount is <= 0");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002516 return;
2517 }
2518
2519 // record the stop time only if currently this is the only
2520 // audio being played
2521 if (mBatteryAudio.refCount == 1) {
2522 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2523 if (mBatteryAudio.deviceOn[i]) {
2524 mBatteryAudio.lastTime[i] += time;
2525 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2526 mBatteryAudio.lastTime[i] = 0;
2527 }
2528 }
2529 }
2530
2531 mBatteryAudio.refCount --;
2532 return;
2533 }
2534
Andy Hung1afd0982016-11-08 16:13:44 -08002535 uid_t uid = IPCThreadState::self()->getCallingUid();
Gloria Wang7cf180c2011-02-19 18:37:57 -08002536 if (uid == AID_MEDIA) {
2537 return;
2538 }
2539 int index = mBatteryData.indexOfKey(uid);
Gloria Wang7cf180c2011-02-19 18:37:57 -08002540
2541 if (index < 0) { // create a new entry for this UID
2542 BatteryUsageInfo info;
2543 info.audioTotalTime = 0;
2544 info.videoTotalTime = 0;
2545 info.audioLastTime = 0;
2546 info.videoLastTime = 0;
2547 info.refCount = 0;
2548
Gloria Wang9ee159b2011-02-24 14:51:45 -08002549 if (mBatteryData.add(uid, info) == NO_MEMORY) {
Steve Block29357bc2012-01-06 19:20:56 +00002550 ALOGE("Battery track error: no memory for new app");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002551 return;
2552 }
Gloria Wang7cf180c2011-02-19 18:37:57 -08002553 }
2554
2555 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
2556
2557 if (params & kBatteryDataCodecStarted) {
2558 if (params & kBatteryDataTrackAudio) {
2559 info.audioLastTime -= time;
2560 info.refCount ++;
2561 }
2562 if (params & kBatteryDataTrackVideo) {
2563 info.videoLastTime -= time;
2564 info.refCount ++;
2565 }
2566 } else {
2567 if (info.refCount == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002568 ALOGW("Battery track warning: refCount is already 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002569 return;
2570 } else if (info.refCount < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00002571 ALOGE("Battery track error: refCount < 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002572 mBatteryData.removeItem(uid);
2573 return;
2574 }
2575
2576 if (params & kBatteryDataTrackAudio) {
2577 info.audioLastTime += time;
2578 info.refCount --;
2579 }
2580 if (params & kBatteryDataTrackVideo) {
2581 info.videoLastTime += time;
2582 info.refCount --;
2583 }
2584
2585 // no stream is being played by this UID
2586 if (info.refCount == 0) {
2587 info.audioTotalTime += info.audioLastTime;
2588 info.audioLastTime = 0;
2589 info.videoTotalTime += info.videoLastTime;
2590 info.videoLastTime = 0;
2591 }
2592 }
2593}
2594
2595status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
2596 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002597
2598 // audio output devices usage
2599 int32_t time = systemTime() / 1000000L; //in ms
2600 int32_t totalTime;
2601
2602 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2603 totalTime = mBatteryAudio.totalTime[i];
2604
2605 if (mBatteryAudio.deviceOn[i]
2606 && (mBatteryAudio.lastTime[i] != 0)) {
2607 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
2608 totalTime += tmpTime;
2609 }
2610
2611 reply->writeInt32(totalTime);
2612 // reset the total time
2613 mBatteryAudio.totalTime[i] = 0;
2614 }
2615
2616 // codec usage
Gloria Wang7cf180c2011-02-19 18:37:57 -08002617 BatteryUsageInfo info;
2618 int size = mBatteryData.size();
2619
2620 reply->writeInt32(size);
2621 int i = 0;
2622
2623 while (i < size) {
2624 info = mBatteryData.valueAt(i);
2625
2626 reply->writeInt32(mBatteryData.keyAt(i)); //UID
2627 reply->writeInt32(info.audioTotalTime);
2628 reply->writeInt32(info.videoTotalTime);
2629
2630 info.audioTotalTime = 0;
2631 info.videoTotalTime = 0;
2632
2633 // remove the UID entry where no stream is being played
2634 if (info.refCount <= 0) {
2635 mBatteryData.removeItemsAt(i);
2636 size --;
2637 i --;
2638 }
2639 i++;
2640 }
2641 return NO_ERROR;
2642}
nikoa64c8c72009-07-20 15:07:26 -07002643} // namespace android