blob: c5f53cb8729de1985da68d735a090e85b80cbf61 [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
Dima Zavin64760242011-05-11 14:15:23 -070065#include <system/audio.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070066
Gloria Wang7cf180c2011-02-19 18:37:57 -080067#include <private/android_filesystem_config.h>
68
James Dong559bf282012-03-28 10:29:14 -070069#include "ActivityManager.h"
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080070#include "MediaRecorderClient.h"
71#include "MediaPlayerService.h"
72#include "MetadataRetrieverClient.h"
John Grossman44a7e422012-06-21 17:29:24 -070073#include "MediaPlayerFactory.h"
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080074
Nicolas Catania14d27472009-07-13 14:37:49 -070075#include "TestPlayerStub.h"
Andreas Huberf9334412010-12-15 15:17:42 -080076#include "nuplayer/NuPlayerDriver.h"
Andreas Huber20111aa2009-07-14 16:56:47 -070077
Andreas Huber20111aa2009-07-14 16:56:47 -070078#include <OMX.h>
Nicolas Catania14d27472009-07-13 14:37:49 -070079
Andreas Hubered3e3e02012-03-26 11:13:27 -070080#include "Crypto.h"
Jeff Tinkercc82dc62013-02-08 10:18:35 -080081#include "Drm.h"
Andreas Huber59451f82012-09-18 10:36:32 -070082#include "HDCP.h"
Andreas Huberb7319a72013-05-29 14:20:52 -070083#include "HTTPBase.h"
Andreas Huber35213f12012-08-29 11:41:50 -070084#include "RemoteDisplay.h"
Andreas Hubered3e3e02012-03-26 11:13:27 -070085
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070086namespace {
nikoa64c8c72009-07-20 15:07:26 -070087using android::media::Metadata;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070088using android::status_t;
89using android::OK;
90using android::BAD_VALUE;
91using android::NOT_ENOUGH_DATA;
92using android::Parcel;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070093
94// Max number of entries in the filter.
95const int kMaxFilterSize = 64; // I pulled that out of thin air.
96
nikoa64c8c72009-07-20 15:07:26 -070097// FIXME: Move all the metadata related function in the Metadata.cpp
nikod608a812009-07-16 16:39:53 -070098
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070099
100// Unmarshall a filter from a Parcel.
101// Filter format in a parcel:
102//
103// 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
104// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
105// | number of entries (n) |
106// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
107// | metadata type 1 |
108// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
109// | metadata type 2 |
110// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
111// ....
112// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
113// | metadata type n |
114// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
115//
116// @param p Parcel that should start with a filter.
117// @param[out] filter On exit contains the list of metadata type to be
118// filtered.
119// @param[out] status On exit contains the status code to be returned.
120// @return true if the parcel starts with a valid filter.
121bool unmarshallFilter(const Parcel& p,
nikoa64c8c72009-07-20 15:07:26 -0700122 Metadata::Filter *filter,
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700123 status_t *status)
124{
Nicolas Catania48290382009-07-10 13:53:06 -0700125 int32_t val;
126 if (p.readInt32(&val) != OK)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700127 {
Steve Block29357bc2012-01-06 19:20:56 +0000128 ALOGE("Failed to read filter's length");
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700129 *status = NOT_ENOUGH_DATA;
130 return false;
131 }
132
Nicolas Catania48290382009-07-10 13:53:06 -0700133 if( val > kMaxFilterSize || val < 0)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700134 {
Steve Block29357bc2012-01-06 19:20:56 +0000135 ALOGE("Invalid filter len %d", val);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700136 *status = BAD_VALUE;
137 return false;
138 }
139
Nicolas Catania48290382009-07-10 13:53:06 -0700140 const size_t num = val;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700141
142 filter->clear();
Nicolas Catania48290382009-07-10 13:53:06 -0700143 filter->setCapacity(num);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700144
nikoa64c8c72009-07-20 15:07:26 -0700145 size_t size = num * sizeof(Metadata::Type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700146
Nicolas Catania48290382009-07-10 13:53:06 -0700147
148 if (p.dataAvail() < size)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700149 {
Steve Block29357bc2012-01-06 19:20:56 +0000150 ALOGE("Filter too short expected %d but got %d", size, p.dataAvail());
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700151 *status = NOT_ENOUGH_DATA;
152 return false;
153 }
154
nikoa64c8c72009-07-20 15:07:26 -0700155 const Metadata::Type *data =
156 static_cast<const Metadata::Type*>(p.readInplace(size));
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700157
Nicolas Catania48290382009-07-10 13:53:06 -0700158 if (NULL == data)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700159 {
Steve Block29357bc2012-01-06 19:20:56 +0000160 ALOGE("Filter had no data");
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700161 *status = BAD_VALUE;
162 return false;
163 }
164
165 // TODO: The stl impl of vector would be more efficient here
166 // because it degenerates into a memcpy on pod types. Try to
167 // replace later or use stl::set.
Nicolas Catania48290382009-07-10 13:53:06 -0700168 for (size_t i = 0; i < num; ++i)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700169 {
Nicolas Catania48290382009-07-10 13:53:06 -0700170 filter->add(*data);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700171 ++data;
172 }
173 *status = OK;
174 return true;
175}
176
Nicolas Catania48290382009-07-10 13:53:06 -0700177// @param filter Of metadata type.
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700178// @param val To be searched.
179// @return true if a match was found.
nikoa64c8c72009-07-20 15:07:26 -0700180bool findMetadata(const Metadata::Filter& filter, const int32_t val)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700181{
182 // Deal with empty and ANY right away
183 if (filter.isEmpty()) return false;
nikoa64c8c72009-07-20 15:07:26 -0700184 if (filter[0] == Metadata::kAny) return true;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700185
Nicolas Catania48290382009-07-10 13:53:06 -0700186 return filter.indexOf(val) >= 0;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700187}
188
189} // anonymous namespace
190
191
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700192namespace {
193using android::Parcel;
194using android::String16;
195
196// marshalling tag indicating flattened utf16 tags
197// keep in sync with frameworks/base/media/java/android/media/AudioAttributes.java
198const int32_t kAudioAttributesMarshallTagFlattenTags = 1;
199
200// Audio attributes format in a parcel:
201//
202// 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
203// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
204// | usage |
205// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
206// | content_type |
207// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Hyejin Kim4f418f92014-09-05 15:50:03 +0900208// | source |
209// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700210// | flags |
211// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
212// | kAudioAttributesMarshallTagFlattenTags | // ignore tags if not found
213// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
214// | flattened tags in UTF16 |
215// | ... |
216// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
217//
218// @param p Parcel that contains audio attributes.
219// @param[out] attributes On exit points to an initialized audio_attributes_t structure
220// @param[out] status On exit contains the status code to be returned.
221void unmarshallAudioAttributes(const Parcel& parcel, audio_attributes_t *attributes)
222{
223 attributes->usage = (audio_usage_t) parcel.readInt32();
224 attributes->content_type = (audio_content_type_t) parcel.readInt32();
Hyejin Kim4f418f92014-09-05 15:50:03 +0900225 attributes->source = (audio_source_t) parcel.readInt32();
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700226 attributes->flags = (audio_flags_mask_t) parcel.readInt32();
227 const bool hasFlattenedTag = (parcel.readInt32() == kAudioAttributesMarshallTagFlattenTags);
228 if (hasFlattenedTag) {
229 // the tags are UTF16, convert to UTF8
230 String16 tags = parcel.readString16();
231 ssize_t realTagSize = utf16_to_utf8_length(tags.string(), tags.size());
232 if (realTagSize <= 0) {
233 strcpy(attributes->tags, "");
234 } else {
235 // copy the flattened string into the attributes as the destination for the conversion:
236 // copying array size -1, array for tags was calloc'd, no need to NULL-terminate it
237 size_t tagSize = realTagSize > AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 ?
238 AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 : realTagSize;
239 utf16_to_utf8(tags.string(), tagSize, attributes->tags);
240 }
241 } else {
242 ALOGE("unmarshallAudioAttributes() received unflattened tags, ignoring tag values");
243 strcpy(attributes->tags, "");
244 }
245}
246} // anonymous namespace
247
248
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800249namespace android {
250
Marco Nelissenf09611f2015-02-13 14:12:42 -0800251extern ALooperRoster gLooperRoster;
252
253
Dave Burked681bbb2011-08-30 14:39:17 +0100254static bool checkPermission(const char* permissionString) {
Dave Burked681bbb2011-08-30 14:39:17 +0100255 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
256 bool ok = checkCallingPermission(String16(permissionString));
Steve Block29357bc2012-01-06 19:20:56 +0000257 if (!ok) ALOGE("Request requires %s", permissionString);
Dave Burked681bbb2011-08-30 14:39:17 +0100258 return ok;
259}
260
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800261// 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 -0800262/* static */ int MediaPlayerService::AudioOutput::mMinBufferCount = 4;
263/* static */ bool MediaPlayerService::AudioOutput::mIsOnEmulator = false;
264
265void MediaPlayerService::instantiate() {
266 defaultServiceManager()->addService(
267 String16("media.player"), new MediaPlayerService());
268}
269
270MediaPlayerService::MediaPlayerService()
271{
Steve Block3856b092011-10-20 11:56:00 +0100272 ALOGV("MediaPlayerService created");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800273 mNextConnId = 1;
Gloria Wang9ee159b2011-02-24 14:51:45 -0800274
275 mBatteryAudio.refCount = 0;
276 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
277 mBatteryAudio.deviceOn[i] = 0;
278 mBatteryAudio.lastTime[i] = 0;
279 mBatteryAudio.totalTime[i] = 0;
280 }
281 // speaker is on by default
282 mBatteryAudio.deviceOn[SPEAKER] = 1;
John Grossman44a7e422012-06-21 17:29:24 -0700283
Chong Zhang0b30fd42014-07-23 14:46:05 -0700284 // reset battery stats
285 // if the mediaserver has crashed, battery stats could be left
286 // in bad state, reset the state upon service start.
Wei Jia3f273d12015-11-24 09:06:49 -0800287 BatteryNotifier::getInstance().noteResetVideo();
Chong Zhang0b30fd42014-07-23 14:46:05 -0700288
John Grossman44a7e422012-06-21 17:29:24 -0700289 MediaPlayerFactory::registerBuiltinFactories();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800290}
291
292MediaPlayerService::~MediaPlayerService()
293{
Steve Block3856b092011-10-20 11:56:00 +0100294 ALOGV("MediaPlayerService destroyed");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800295}
296
Svet Ganovbe71aa22015-04-28 12:06:02 -0700297sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(const String16 &opPackageName)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800298{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800299 pid_t pid = IPCThreadState::self()->getCallingPid();
Svet Ganovbe71aa22015-04-28 12:06:02 -0700300 sp<MediaRecorderClient> recorder = new MediaRecorderClient(this, pid, opPackageName);
Gloria Wangdac6a312009-10-29 15:46:37 -0700301 wp<MediaRecorderClient> w = recorder;
302 Mutex::Autolock lock(mLock);
303 mMediaRecorderClients.add(w);
Steve Block3856b092011-10-20 11:56:00 +0100304 ALOGV("Create new media recorder client from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800305 return recorder;
306}
307
Gloria Wangdac6a312009-10-29 15:46:37 -0700308void MediaPlayerService::removeMediaRecorderClient(wp<MediaRecorderClient> client)
309{
310 Mutex::Autolock lock(mLock);
311 mMediaRecorderClients.remove(client);
Steve Block3856b092011-10-20 11:56:00 +0100312 ALOGV("Delete media recorder client");
Gloria Wangdac6a312009-10-29 15:46:37 -0700313}
314
Glenn Kastenf37971f2012-02-03 11:06:53 -0800315sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800316{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800317 pid_t pid = IPCThreadState::self()->getCallingPid();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800318 sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
Steve Block3856b092011-10-20 11:56:00 +0100319 ALOGV("Create new media retriever from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800320 return retriever;
321}
322
Glenn Kastenf37971f2012-02-03 11:06:53 -0800323sp<IMediaPlayer> MediaPlayerService::create(const sp<IMediaPlayerClient>& client,
Dave Burked681bbb2011-08-30 14:39:17 +0100324 int audioSessionId)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800325{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800326 pid_t pid = IPCThreadState::self()->getCallingPid();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800327 int32_t connId = android_atomic_inc(&mNextConnId);
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700328
329 sp<Client> c = new Client(
330 this, pid, connId, client, audioSessionId,
331 IPCThreadState::self()->getCallingUid());
332
Steve Block3856b092011-10-20 11:56:00 +0100333 ALOGV("Create new client(%d) from pid %d, uid %d, ", connId, pid,
Dave Burked681bbb2011-08-30 14:39:17 +0100334 IPCThreadState::self()->getCallingUid());
335
336 wp<Client> w = c;
337 {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800338 Mutex::Autolock lock(mLock);
339 mClients.add(w);
340 }
Andreas Hubere2b10282010-11-23 11:41:34 -0800341 return c;
342}
343
Lajos Molnar1381d4b2014-08-07 15:18:35 -0700344sp<IMediaCodecList> MediaPlayerService::getCodecList() const {
345 return MediaCodecList::getLocalInstance();
346}
347
Marco Nelissen260e56c2016-01-28 21:41:25 +0000348sp<IOMX> MediaPlayerService::getOMX() {
349 Mutex::Autolock autoLock(mLock);
350
351 if (mOMX.get() == NULL) {
352 mOMX = new OMX;
353 }
354
355 return mOMX;
356}
357
Andreas Hubered3e3e02012-03-26 11:13:27 -0700358sp<ICrypto> MediaPlayerService::makeCrypto() {
Andreas Huber1bd139a2012-04-03 14:19:20 -0700359 return new Crypto;
Andreas Hubered3e3e02012-03-26 11:13:27 -0700360}
361
Jeff Tinkercc82dc62013-02-08 10:18:35 -0800362sp<IDrm> MediaPlayerService::makeDrm() {
363 return new Drm;
364}
365
Andreas Huber279dcd82013-01-30 10:41:25 -0800366sp<IHDCP> MediaPlayerService::makeHDCP(bool createEncryptionModule) {
367 return new HDCP(createEncryptionModule);
Andreas Huber59451f82012-09-18 10:36:32 -0700368}
369
Jeff Brown2013a542012-09-04 21:38:42 -0700370sp<IRemoteDisplay> MediaPlayerService::listenForRemoteDisplay(
Svet Ganovbe71aa22015-04-28 12:06:02 -0700371 const String16 &opPackageName,
Jeff Brown2013a542012-09-04 21:38:42 -0700372 const sp<IRemoteDisplayClient>& client, const String8& iface) {
Jeff Brownaba33d52012-09-07 17:38:58 -0700373 if (!checkPermission("android.permission.CONTROL_WIFI_DISPLAY")) {
374 return NULL;
375 }
376
Svet Ganovbe71aa22015-04-28 12:06:02 -0700377 return new RemoteDisplay(opPackageName, client, iface.string());
Jeff Brown2013a542012-09-04 21:38:42 -0700378}
379
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800380status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
381{
382 const size_t SIZE = 256;
383 char buffer[SIZE];
384 String8 result;
385
386 result.append(" AudioOutput\n");
387 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n",
388 mStreamType, mLeftVolume, mRightVolume);
389 result.append(buffer);
390 snprintf(buffer, 255, " msec per frame(%f), latency (%d)\n",
Eric Laurentdb354e52012-03-05 17:27:11 -0800391 mMsecsPerFrame, (mTrack != 0) ? mTrack->latency() : -1);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800392 result.append(buffer);
Eric Laurent2beeb502010-07-16 07:43:46 -0700393 snprintf(buffer, 255, " aux effect id(%d), send level (%f)\n",
394 mAuxEffectId, mSendLevel);
395 result.append(buffer);
396
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800397 ::write(fd, result.string(), result.size());
398 if (mTrack != 0) {
399 mTrack->dump(fd, args);
400 }
401 return NO_ERROR;
402}
403
Lajos Molnar6d339f12015-04-17 16:15:53 -0700404status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800405{
406 const size_t SIZE = 256;
407 char buffer[SIZE];
408 String8 result;
409 result.append(" Client\n");
410 snprintf(buffer, 255, " pid(%d), connId(%d), status(%d), looping(%s)\n",
411 mPid, mConnId, mStatus, mLoop?"true": "false");
412 result.append(buffer);
413 write(fd, result.string(), result.size());
Andreas Hubera0b1d4b2011-06-07 15:52:25 -0700414 if (mPlayer != NULL) {
415 mPlayer->dump(fd, args);
416 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800417 if (mAudioOutput != 0) {
418 mAudioOutput->dump(fd, args);
419 }
420 write(fd, "\n", 1);
421 return NO_ERROR;
422}
423
Marco Nelissenf09611f2015-02-13 14:12:42 -0800424/**
425 * The only arguments this understands right now are -c, -von and -voff,
426 * which are parsed by ALooperRoster::dump()
427 */
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800428status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
429{
430 const size_t SIZE = 256;
431 char buffer[SIZE];
432 String8 result;
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530433 SortedVector< sp<Client> > clients; //to serialise the mutex unlock & client destruction.
434 SortedVector< sp<MediaRecorderClient> > mediaRecorderClients;
435
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800436 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
437 snprintf(buffer, SIZE, "Permission Denial: "
438 "can't dump MediaPlayerService from pid=%d, uid=%d\n",
439 IPCThreadState::self()->getCallingPid(),
440 IPCThreadState::self()->getCallingUid());
441 result.append(buffer);
442 } else {
443 Mutex::Autolock lock(mLock);
444 for (int i = 0, n = mClients.size(); i < n; ++i) {
445 sp<Client> c = mClients[i].promote();
446 if (c != 0) c->dump(fd, args);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530447 clients.add(c);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800448 }
James Dongb9141222010-07-08 11:16:11 -0700449 if (mMediaRecorderClients.size() == 0) {
450 result.append(" No media recorder client\n\n");
451 } else {
452 for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
453 sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
James Donge579e282011-10-18 22:29:20 -0700454 if (c != 0) {
455 snprintf(buffer, 255, " MediaRecorderClient pid(%d)\n", c->mPid);
456 result.append(buffer);
457 write(fd, result.string(), result.size());
458 result = "\n";
459 c->dump(fd, args);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530460 mediaRecorderClients.add(c);
James Donge579e282011-10-18 22:29:20 -0700461 }
James Dongb9141222010-07-08 11:16:11 -0700462 }
Gloria Wangdac6a312009-10-29 15:46:37 -0700463 }
464
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800465 result.append(" Files opened and/or mapped:\n");
Marco Nelissenf09611f2015-02-13 14:12:42 -0800466 snprintf(buffer, SIZE, "/proc/%d/maps", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800467 FILE *f = fopen(buffer, "r");
468 if (f) {
469 while (!feof(f)) {
470 fgets(buffer, SIZE, f);
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700471 if (strstr(buffer, " /storage/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800472 strstr(buffer, " /system/sounds/") ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700473 strstr(buffer, " /data/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800474 strstr(buffer, " /system/media/")) {
475 result.append(" ");
476 result.append(buffer);
477 }
478 }
479 fclose(f);
480 } else {
481 result.append("couldn't open ");
482 result.append(buffer);
483 result.append("\n");
484 }
485
Marco Nelissenf09611f2015-02-13 14:12:42 -0800486 snprintf(buffer, SIZE, "/proc/%d/fd", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800487 DIR *d = opendir(buffer);
488 if (d) {
489 struct dirent *ent;
490 while((ent = readdir(d)) != NULL) {
491 if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
Marco Nelissenf09611f2015-02-13 14:12:42 -0800492 snprintf(buffer, SIZE, "/proc/%d/fd/%s", getpid(), ent->d_name);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800493 struct stat s;
494 if (lstat(buffer, &s) == 0) {
495 if ((s.st_mode & S_IFMT) == S_IFLNK) {
496 char linkto[256];
497 int len = readlink(buffer, linkto, sizeof(linkto));
498 if(len > 0) {
499 if(len > 255) {
500 linkto[252] = '.';
501 linkto[253] = '.';
502 linkto[254] = '.';
503 linkto[255] = 0;
504 } else {
505 linkto[len] = 0;
506 }
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700507 if (strstr(linkto, "/storage/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800508 strstr(linkto, "/system/sounds/") == linkto ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700509 strstr(linkto, "/data/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800510 strstr(linkto, "/system/media/") == linkto) {
511 result.append(" ");
512 result.append(buffer);
513 result.append(" -> ");
514 result.append(linkto);
515 result.append("\n");
516 }
517 }
518 } else {
519 result.append(" unexpected type for ");
520 result.append(buffer);
521 result.append("\n");
522 }
523 }
524 }
525 }
526 closedir(d);
527 } else {
528 result.append("couldn't open ");
529 result.append(buffer);
530 result.append("\n");
531 }
532
Marco Nelissenf09611f2015-02-13 14:12:42 -0800533 gLooperRoster.dump(fd, args);
534
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800535 bool dumpMem = false;
536 for (size_t i = 0; i < args.size(); i++) {
537 if (args[i] == String16("-m")) {
538 dumpMem = true;
539 }
540 }
541 if (dumpMem) {
James Dong8635b7b2011-03-14 17:01:38 -0700542 dumpMemoryAddresses(fd);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800543 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800544 }
545 write(fd, result.string(), result.size());
546 return NO_ERROR;
547}
548
549void MediaPlayerService::removeClient(wp<Client> client)
550{
551 Mutex::Autolock lock(mLock);
552 mClients.remove(client);
553}
554
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700555MediaPlayerService::Client::Client(
556 const sp<MediaPlayerService>& service, pid_t pid,
557 int32_t connId, const sp<IMediaPlayerClient>& client,
558 int audioSessionId, uid_t uid)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800559{
Steve Block3856b092011-10-20 11:56:00 +0100560 ALOGV("Client(%d) constructor", connId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800561 mPid = pid;
562 mConnId = connId;
563 mService = service;
564 mClient = client;
565 mLoop = false;
566 mStatus = NO_INIT;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700567 mAudioSessionId = audioSessionId;
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700568 mUID = uid;
John Grossmanc795b642012-02-22 15:38:35 -0800569 mRetransmitEndpointValid = false;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700570 mAudioAttributes = NULL;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700571
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800572#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000573 ALOGD("create Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800574 mAntagonizer = new Antagonizer(notify, this);
575#endif
576}
577
578MediaPlayerService::Client::~Client()
579{
Steve Block3856b092011-10-20 11:56:00 +0100580 ALOGV("Client(%d) destructor pid = %d", mConnId, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800581 mAudioOutput.clear();
582 wp<Client> client(this);
583 disconnect();
584 mService->removeClient(client);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700585 if (mAudioAttributes != NULL) {
586 free(mAudioAttributes);
587 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800588}
589
590void MediaPlayerService::Client::disconnect()
591{
Steve Block3856b092011-10-20 11:56:00 +0100592 ALOGV("disconnect(%d) from pid %d", mConnId, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800593 // grab local reference and clear main reference to prevent future
594 // access to object
595 sp<MediaPlayerBase> p;
596 {
597 Mutex::Autolock l(mLock);
598 p = mPlayer;
beanzdcfefde2012-11-05 09:51:43 +0800599 mClient.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800600 }
Andreas Huber20111aa2009-07-14 16:56:47 -0700601
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800602 mPlayer.clear();
603
604 // clear the notification to prevent callbacks to dead client
605 // and reset the player. We assume the player will serialize
606 // access to itself if necessary.
607 if (p != 0) {
608 p->setNotifyCallback(0, 0);
609#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000610 ALOGD("kill Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800611 mAntagonizer->kill();
612#endif
613 p->reset();
614 }
615
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700616 disconnectNativeWindow();
617
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800618 IPCThreadState::self()->flushCommands();
619}
620
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800621sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
622{
623 // determine if we have the right player type
624 sp<MediaPlayerBase> p = mPlayer;
625 if ((p != NULL) && (p->playerType() != playerType)) {
Steve Block3856b092011-10-20 11:56:00 +0100626 ALOGV("delete player");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800627 p.clear();
628 }
629 if (p == NULL) {
Ronghua Wu68845c12015-07-21 09:50:48 -0700630 p = MediaPlayerFactory::createPlayer(playerType, this, notify, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800631 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700632
Jason Simmonsdb29e522011-08-12 13:46:55 -0700633 if (p != NULL) {
634 p->setUID(mUID);
635 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700636
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800637 return p;
638}
639
John Grossmanc795b642012-02-22 15:38:35 -0800640sp<MediaPlayerBase> MediaPlayerService::Client::setDataSource_pre(
641 player_type playerType)
642{
643 ALOGV("player type = %d", playerType);
644
645 // create the right type of player
646 sp<MediaPlayerBase> p = createPlayer(playerType);
647 if (p == NULL) {
648 return p;
649 }
650
651 if (!p->hardwareOutput()) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -0700652 Mutex::Autolock l(mLock);
Marco Nelissend457c972014-02-11 08:47:07 -0800653 mAudioOutput = new AudioOutput(mAudioSessionId, IPCThreadState::self()->getCallingUid(),
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700654 mPid, mAudioAttributes);
John Grossmanc795b642012-02-22 15:38:35 -0800655 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
656 }
657
658 return p;
659}
660
661void MediaPlayerService::Client::setDataSource_post(
662 const sp<MediaPlayerBase>& p,
663 status_t status)
664{
665 ALOGV(" setDataSource");
666 mStatus = status;
667 if (mStatus != OK) {
668 ALOGE(" error: %d", mStatus);
669 return;
670 }
671
672 // Set the re-transmission endpoint if one was chosen.
673 if (mRetransmitEndpointValid) {
674 mStatus = p->setRetransmitEndpoint(&mRetransmitEndpoint);
675 if (mStatus != NO_ERROR) {
676 ALOGE("setRetransmitEndpoint error: %d", mStatus);
677 }
678 }
679
680 if (mStatus == OK) {
681 mPlayer = p;
682 }
683}
684
Andreas Huber2db84552010-01-28 11:19:57 -0800685status_t MediaPlayerService::Client::setDataSource(
Andreas Huber1b86fe02014-01-29 11:13:26 -0800686 const sp<IMediaHTTPService> &httpService,
687 const char *url,
688 const KeyedVector<String8, String8> *headers)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800689{
Steve Block3856b092011-10-20 11:56:00 +0100690 ALOGV("setDataSource(%s)", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800691 if (url == NULL)
692 return UNKNOWN_ERROR;
693
Dave Burked681bbb2011-08-30 14:39:17 +0100694 if ((strncmp(url, "http://", 7) == 0) ||
695 (strncmp(url, "https://", 8) == 0) ||
696 (strncmp(url, "rtsp://", 7) == 0)) {
697 if (!checkPermission("android.permission.INTERNET")) {
698 return PERMISSION_DENIED;
699 }
700 }
701
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800702 if (strncmp(url, "content://", 10) == 0) {
703 // get a filedescriptor for the content Uri and
704 // pass it to the setDataSource(fd) method
705
706 String16 url16(url);
707 int fd = android::openContentProviderFile(url16);
708 if (fd < 0)
709 {
Steve Block29357bc2012-01-06 19:20:56 +0000710 ALOGE("Couldn't open fd for %s", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800711 return UNKNOWN_ERROR;
712 }
713 setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
714 close(fd);
715 return mStatus;
716 } else {
John Grossman44a7e422012-06-21 17:29:24 -0700717 player_type playerType = MediaPlayerFactory::getPlayerType(this, url);
John Grossmanc795b642012-02-22 15:38:35 -0800718 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
719 if (p == NULL) {
720 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800721 }
722
Andreas Huber1b86fe02014-01-29 11:13:26 -0800723 setDataSource_post(p, p->setDataSource(httpService, url, headers));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800724 return mStatus;
725 }
726}
727
728status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
729{
Marco Nelissen83b0fd92015-09-16 13:48:07 -0700730 ALOGV("setDataSource fd=%d (%s), offset=%lld, length=%lld",
731 fd, nameForFd(fd).c_str(), (long long) offset, (long long) length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800732 struct stat sb;
733 int ret = fstat(fd, &sb);
734 if (ret != 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000735 ALOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800736 return UNKNOWN_ERROR;
737 }
738
Ying Wang5fde15d2015-04-20 22:13:22 -0700739 ALOGV("st_dev = %llu", static_cast<uint64_t>(sb.st_dev));
Steve Block3856b092011-10-20 11:56:00 +0100740 ALOGV("st_mode = %u", sb.st_mode);
Mark Salyzyn77342f72014-06-18 16:31:32 -0700741 ALOGV("st_uid = %lu", static_cast<unsigned long>(sb.st_uid));
742 ALOGV("st_gid = %lu", static_cast<unsigned long>(sb.st_gid));
Steve Block3856b092011-10-20 11:56:00 +0100743 ALOGV("st_size = %llu", sb.st_size);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800744
745 if (offset >= sb.st_size) {
Steve Block29357bc2012-01-06 19:20:56 +0000746 ALOGE("offset error");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800747 return UNKNOWN_ERROR;
748 }
749 if (offset + length > sb.st_size) {
750 length = sb.st_size - offset;
Steve Block3856b092011-10-20 11:56:00 +0100751 ALOGV("calculated length = %lld", length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800752 }
753
John Grossman44a7e422012-06-21 17:29:24 -0700754 player_type playerType = MediaPlayerFactory::getPlayerType(this,
755 fd,
756 offset,
757 length);
John Grossmanc795b642012-02-22 15:38:35 -0800758 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
759 if (p == NULL) {
760 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800761 }
762
763 // now set data source
John Grossmanc795b642012-02-22 15:38:35 -0800764 setDataSource_post(p, p->setDataSource(fd, offset, length));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800765 return mStatus;
766}
767
Andreas Hubere2b10282010-11-23 11:41:34 -0800768status_t MediaPlayerService::Client::setDataSource(
769 const sp<IStreamSource> &source) {
770 // create the right type of player
John Grossman44a7e422012-06-21 17:29:24 -0700771 player_type playerType = MediaPlayerFactory::getPlayerType(this, source);
John Grossmanc795b642012-02-22 15:38:35 -0800772 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
Andreas Hubere2b10282010-11-23 11:41:34 -0800773 if (p == NULL) {
774 return NO_INIT;
775 }
776
Andreas Hubere2b10282010-11-23 11:41:34 -0800777 // now set data source
John Grossmanc795b642012-02-22 15:38:35 -0800778 setDataSource_post(p, p->setDataSource(source));
Andreas Hubere2b10282010-11-23 11:41:34 -0800779 return mStatus;
780}
781
Chris Watkins99f31602015-03-20 13:06:33 -0700782status_t MediaPlayerService::Client::setDataSource(
783 const sp<IDataSource> &source) {
784 sp<DataSource> dataSource = DataSource::CreateFromIDataSource(source);
785 player_type playerType = MediaPlayerFactory::getPlayerType(this, dataSource);
786 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
787 if (p == NULL) {
788 return NO_INIT;
789 }
790 // now set data source
791 setDataSource_post(p, p->setDataSource(dataSource));
792 return mStatus;
793}
794
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700795void MediaPlayerService::Client::disconnectNativeWindow() {
796 if (mConnectedWindow != NULL) {
797 status_t err = native_window_api_disconnect(mConnectedWindow.get(),
798 NATIVE_WINDOW_API_MEDIA);
799
800 if (err != OK) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000801 ALOGW("native_window_api_disconnect returned an error: %s (%d)",
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700802 strerror(-err), err);
803 }
804 }
805 mConnectedWindow.clear();
806}
807
Glenn Kasten11731182011-02-08 17:26:17 -0800808status_t MediaPlayerService::Client::setVideoSurfaceTexture(
Andy McFadden484566c2012-12-18 09:46:54 -0800809 const sp<IGraphicBufferProducer>& bufferProducer)
Glenn Kasten11731182011-02-08 17:26:17 -0800810{
Andy McFadden484566c2012-12-18 09:46:54 -0800811 ALOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, bufferProducer.get());
Glenn Kasten11731182011-02-08 17:26:17 -0800812 sp<MediaPlayerBase> p = getPlayer();
813 if (p == 0) return UNKNOWN_ERROR;
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700814
Marco Nelissenf8880202014-11-14 07:58:25 -0800815 sp<IBinder> binder(IInterface::asBinder(bufferProducer));
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700816 if (mConnectedWindowBinder == binder) {
817 return OK;
818 }
819
820 sp<ANativeWindow> anw;
Andy McFadden484566c2012-12-18 09:46:54 -0800821 if (bufferProducer != NULL) {
Marco Nelissenee08f7e2013-09-16 13:30:01 -0700822 anw = new Surface(bufferProducer, true /* controlledByApp */);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700823 status_t err = native_window_api_connect(anw.get(),
824 NATIVE_WINDOW_API_MEDIA);
825
826 if (err != OK) {
Steve Block29357bc2012-01-06 19:20:56 +0000827 ALOGE("setVideoSurfaceTexture failed: %d", err);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700828 // Note that we must do the reset before disconnecting from the ANW.
829 // Otherwise queue/dequeue calls could be made on the disconnected
830 // ANW, which may result in errors.
831 reset();
832
833 disconnectNativeWindow();
834
835 return err;
836 }
837 }
838
Andy McFadden484566c2012-12-18 09:46:54 -0800839 // Note that we must set the player's new GraphicBufferProducer before
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700840 // disconnecting the old one. Otherwise queue/dequeue calls could be made
841 // on the disconnected ANW, which may result in errors.
Andy McFadden484566c2012-12-18 09:46:54 -0800842 status_t err = p->setVideoSurfaceTexture(bufferProducer);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700843
844 disconnectNativeWindow();
845
846 mConnectedWindow = anw;
847
848 if (err == OK) {
849 mConnectedWindowBinder = binder;
850 } else {
851 disconnectNativeWindow();
852 }
853
854 return err;
Glenn Kasten11731182011-02-08 17:26:17 -0800855}
856
Nicolas Catania1d187f12009-05-12 23:25:55 -0700857status_t MediaPlayerService::Client::invoke(const Parcel& request,
858 Parcel *reply)
859{
860 sp<MediaPlayerBase> p = getPlayer();
861 if (p == NULL) return UNKNOWN_ERROR;
862 return p->invoke(request, reply);
863}
864
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700865// This call doesn't need to access the native player.
866status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
867{
868 status_t status;
nikoa64c8c72009-07-20 15:07:26 -0700869 media::Metadata::Filter allow, drop;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700870
Nicolas Catania48290382009-07-10 13:53:06 -0700871 if (unmarshallFilter(filter, &allow, &status) &&
872 unmarshallFilter(filter, &drop, &status)) {
873 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700874
875 mMetadataAllow = allow;
876 mMetadataDrop = drop;
877 }
878 return status;
879}
880
Nicolas Catania48290382009-07-10 13:53:06 -0700881status_t MediaPlayerService::Client::getMetadata(
Mark Salyzyn77342f72014-06-18 16:31:32 -0700882 bool update_only, bool /*apply_filter*/, Parcel *reply)
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700883{
nikoa64c8c72009-07-20 15:07:26 -0700884 sp<MediaPlayerBase> player = getPlayer();
885 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania48290382009-07-10 13:53:06 -0700886
nikod608a812009-07-16 16:39:53 -0700887 status_t status;
888 // Placeholder for the return code, updated by the caller.
889 reply->writeInt32(-1);
890
nikoa64c8c72009-07-20 15:07:26 -0700891 media::Metadata::Filter ids;
Nicolas Catania48290382009-07-10 13:53:06 -0700892
893 // We don't block notifications while we fetch the data. We clear
894 // mMetadataUpdated first so we don't lose notifications happening
895 // during the rest of this call.
896 {
897 Mutex::Autolock lock(mLock);
898 if (update_only) {
nikod608a812009-07-16 16:39:53 -0700899 ids = mMetadataUpdated;
Nicolas Catania48290382009-07-10 13:53:06 -0700900 }
901 mMetadataUpdated.clear();
902 }
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700903
nikoa64c8c72009-07-20 15:07:26 -0700904 media::Metadata metadata(reply);
Nicolas Catania48290382009-07-10 13:53:06 -0700905
nikoa64c8c72009-07-20 15:07:26 -0700906 metadata.appendHeader();
907 status = player->getMetadata(ids, reply);
nikod608a812009-07-16 16:39:53 -0700908
909 if (status != OK) {
nikoa64c8c72009-07-20 15:07:26 -0700910 metadata.resetParcel();
Steve Block29357bc2012-01-06 19:20:56 +0000911 ALOGE("getMetadata failed %d", status);
nikod608a812009-07-16 16:39:53 -0700912 return status;
913 }
914
915 // FIXME: Implement filtering on the result. Not critical since
916 // filtering takes place on the update notifications already. This
917 // would be when all the metadata are fetch and a filter is set.
918
nikod608a812009-07-16 16:39:53 -0700919 // Everything is fine, update the metadata length.
nikoa64c8c72009-07-20 15:07:26 -0700920 metadata.updateLength();
nikod608a812009-07-16 16:39:53 -0700921 return OK;
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700922}
923
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800924status_t MediaPlayerService::Client::prepareAsync()
925{
Steve Block3856b092011-10-20 11:56:00 +0100926 ALOGV("[%d] prepareAsync", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800927 sp<MediaPlayerBase> p = getPlayer();
928 if (p == 0) return UNKNOWN_ERROR;
929 status_t ret = p->prepareAsync();
930#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000931 ALOGD("start Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800932 if (ret == NO_ERROR) mAntagonizer->start();
933#endif
934 return ret;
935}
936
937status_t MediaPlayerService::Client::start()
938{
Steve Block3856b092011-10-20 11:56:00 +0100939 ALOGV("[%d] start", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800940 sp<MediaPlayerBase> p = getPlayer();
941 if (p == 0) return UNKNOWN_ERROR;
942 p->setLooping(mLoop);
943 return p->start();
944}
945
946status_t MediaPlayerService::Client::stop()
947{
Steve Block3856b092011-10-20 11:56:00 +0100948 ALOGV("[%d] stop", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800949 sp<MediaPlayerBase> p = getPlayer();
950 if (p == 0) return UNKNOWN_ERROR;
951 return p->stop();
952}
953
954status_t MediaPlayerService::Client::pause()
955{
Steve Block3856b092011-10-20 11:56:00 +0100956 ALOGV("[%d] pause", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800957 sp<MediaPlayerBase> p = getPlayer();
958 if (p == 0) return UNKNOWN_ERROR;
959 return p->pause();
960}
961
962status_t MediaPlayerService::Client::isPlaying(bool* state)
963{
964 *state = false;
965 sp<MediaPlayerBase> p = getPlayer();
966 if (p == 0) return UNKNOWN_ERROR;
967 *state = p->isPlaying();
Steve Block3856b092011-10-20 11:56:00 +0100968 ALOGV("[%d] isPlaying: %d", mConnId, *state);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800969 return NO_ERROR;
970}
971
Lajos Molnar3a474aa2015-04-24 17:10:07 -0700972status_t MediaPlayerService::Client::setPlaybackSettings(const AudioPlaybackRate& rate)
Wei Jia98160162015-02-04 17:01:11 -0800973{
Lajos Molnar3a474aa2015-04-24 17:10:07 -0700974 ALOGV("[%d] setPlaybackSettings(%f, %f, %d, %d)",
975 mConnId, rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Wei Jia98160162015-02-04 17:01:11 -0800976 sp<MediaPlayerBase> p = getPlayer();
977 if (p == 0) return UNKNOWN_ERROR;
Lajos Molnar3a474aa2015-04-24 17:10:07 -0700978 return p->setPlaybackSettings(rate);
979}
980
981status_t MediaPlayerService::Client::getPlaybackSettings(AudioPlaybackRate* rate /* nonnull */)
982{
983 sp<MediaPlayerBase> p = getPlayer();
984 if (p == 0) return UNKNOWN_ERROR;
985 status_t ret = p->getPlaybackSettings(rate);
986 if (ret == NO_ERROR) {
987 ALOGV("[%d] getPlaybackSettings(%f, %f, %d, %d)",
988 mConnId, rate->mSpeed, rate->mPitch, rate->mFallbackMode, rate->mStretchMode);
989 } else {
990 ALOGV("[%d] getPlaybackSettings returned %d", mConnId, ret);
991 }
992 return ret;
993}
994
995status_t MediaPlayerService::Client::setSyncSettings(
996 const AVSyncSettings& sync, float videoFpsHint)
997{
998 ALOGV("[%d] setSyncSettings(%u, %u, %f, %f)",
999 mConnId, sync.mSource, sync.mAudioAdjustMode, sync.mTolerance, videoFpsHint);
1000 sp<MediaPlayerBase> p = getPlayer();
1001 if (p == 0) return UNKNOWN_ERROR;
1002 return p->setSyncSettings(sync, videoFpsHint);
1003}
1004
1005status_t MediaPlayerService::Client::getSyncSettings(
1006 AVSyncSettings* sync /* nonnull */, float* videoFps /* nonnull */)
1007{
1008 sp<MediaPlayerBase> p = getPlayer();
1009 if (p == 0) return UNKNOWN_ERROR;
1010 status_t ret = p->getSyncSettings(sync, videoFps);
1011 if (ret == NO_ERROR) {
1012 ALOGV("[%d] getSyncSettings(%u, %u, %f, %f)",
1013 mConnId, sync->mSource, sync->mAudioAdjustMode, sync->mTolerance, *videoFps);
1014 } else {
1015 ALOGV("[%d] getSyncSettings returned %d", mConnId, ret);
1016 }
1017 return ret;
Wei Jia98160162015-02-04 17:01:11 -08001018}
1019
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001020status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
1021{
Steve Block3856b092011-10-20 11:56:00 +01001022 ALOGV("getCurrentPosition");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001023 sp<MediaPlayerBase> p = getPlayer();
1024 if (p == 0) return UNKNOWN_ERROR;
1025 status_t ret = p->getCurrentPosition(msec);
1026 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001027 ALOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001028 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001029 ALOGE("getCurrentPosition returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001030 }
1031 return ret;
1032}
1033
1034status_t MediaPlayerService::Client::getDuration(int *msec)
1035{
Steve Block3856b092011-10-20 11:56:00 +01001036 ALOGV("getDuration");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001037 sp<MediaPlayerBase> p = getPlayer();
1038 if (p == 0) return UNKNOWN_ERROR;
1039 status_t ret = p->getDuration(msec);
1040 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001041 ALOGV("[%d] getDuration = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001042 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001043 ALOGE("getDuration returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001044 }
1045 return ret;
1046}
1047
Marco Nelissen6b74d672012-02-28 16:07:44 -08001048status_t MediaPlayerService::Client::setNextPlayer(const sp<IMediaPlayer>& player) {
1049 ALOGV("setNextPlayer");
1050 Mutex::Autolock l(mLock);
1051 sp<Client> c = static_cast<Client*>(player.get());
1052 mNextClient = c;
John Grossman5f7e55e2012-08-24 14:47:25 -07001053
1054 if (c != NULL) {
1055 if (mAudioOutput != NULL) {
1056 mAudioOutput->setNextOutput(c->mAudioOutput);
1057 } else if ((mPlayer != NULL) && !mPlayer->hardwareOutput()) {
1058 ALOGE("no current audio output");
1059 }
1060
1061 if ((mPlayer != NULL) && (mNextClient->getPlayer() != NULL)) {
1062 mPlayer->setNextPlayer(mNextClient->getPlayer());
1063 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001064 }
John Grossman5f7e55e2012-08-24 14:47:25 -07001065
Marco Nelissen6b74d672012-02-28 16:07:44 -08001066 return OK;
1067}
1068
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001069status_t MediaPlayerService::Client::seekTo(int msec)
1070{
Steve Block3856b092011-10-20 11:56:00 +01001071 ALOGV("[%d] seekTo(%d)", mConnId, msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001072 sp<MediaPlayerBase> p = getPlayer();
1073 if (p == 0) return UNKNOWN_ERROR;
1074 return p->seekTo(msec);
1075}
1076
1077status_t MediaPlayerService::Client::reset()
1078{
Steve Block3856b092011-10-20 11:56:00 +01001079 ALOGV("[%d] reset", mConnId);
John Grossmanc795b642012-02-22 15:38:35 -08001080 mRetransmitEndpointValid = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001081 sp<MediaPlayerBase> p = getPlayer();
1082 if (p == 0) return UNKNOWN_ERROR;
1083 return p->reset();
1084}
1085
Glenn Kastenfff6d712012-01-12 16:38:12 -08001086status_t MediaPlayerService::Client::setAudioStreamType(audio_stream_type_t type)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001087{
Steve Block3856b092011-10-20 11:56:00 +01001088 ALOGV("[%d] setAudioStreamType(%d)", mConnId, type);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001089 // TODO: for hardware output, call player instead
1090 Mutex::Autolock l(mLock);
1091 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1092 return NO_ERROR;
1093}
1094
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001095status_t MediaPlayerService::Client::setAudioAttributes_l(const Parcel &parcel)
1096{
1097 if (mAudioAttributes != NULL) { free(mAudioAttributes); }
1098 mAudioAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001099 if (mAudioAttributes == NULL) {
1100 return NO_MEMORY;
1101 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001102 unmarshallAudioAttributes(parcel, mAudioAttributes);
1103
1104 ALOGV("setAudioAttributes_l() usage=%d content=%d flags=0x%x tags=%s",
1105 mAudioAttributes->usage, mAudioAttributes->content_type, mAudioAttributes->flags,
1106 mAudioAttributes->tags);
1107
1108 if (mAudioOutput != 0) {
1109 mAudioOutput->setAudioAttributes(mAudioAttributes);
1110 }
1111 return NO_ERROR;
1112}
1113
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001114status_t MediaPlayerService::Client::setLooping(int loop)
1115{
Steve Block3856b092011-10-20 11:56:00 +01001116 ALOGV("[%d] setLooping(%d)", mConnId, loop);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001117 mLoop = loop;
1118 sp<MediaPlayerBase> p = getPlayer();
1119 if (p != 0) return p->setLooping(loop);
1120 return NO_ERROR;
1121}
1122
1123status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1124{
Steve Block3856b092011-10-20 11:56:00 +01001125 ALOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
John Grossman761defc2012-02-09 15:09:05 -08001126
1127 // for hardware output, call player instead
1128 sp<MediaPlayerBase> p = getPlayer();
1129 {
1130 Mutex::Autolock l(mLock);
1131 if (p != 0 && p->hardwareOutput()) {
1132 MediaPlayerHWInterface* hwp =
1133 reinterpret_cast<MediaPlayerHWInterface*>(p.get());
1134 return hwp->setVolume(leftVolume, rightVolume);
1135 } else {
1136 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1137 return NO_ERROR;
1138 }
1139 }
1140
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001141 return NO_ERROR;
1142}
1143
Eric Laurent2beeb502010-07-16 07:43:46 -07001144status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1145{
Steve Block3856b092011-10-20 11:56:00 +01001146 ALOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
Eric Laurent2beeb502010-07-16 07:43:46 -07001147 Mutex::Autolock l(mLock);
1148 if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1149 return NO_ERROR;
1150}
1151
1152status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1153{
Steve Block3856b092011-10-20 11:56:00 +01001154 ALOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
Eric Laurent2beeb502010-07-16 07:43:46 -07001155 Mutex::Autolock l(mLock);
1156 if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1157 return NO_ERROR;
1158}
Nicolas Catania48290382009-07-10 13:53:06 -07001159
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001160status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
Steve Block3856b092011-10-20 11:56:00 +01001161 ALOGV("[%d] setParameter(%d)", mConnId, key);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001162 switch (key) {
1163 case KEY_PARAMETER_AUDIO_ATTRIBUTES:
1164 {
1165 Mutex::Autolock l(mLock);
1166 return setAudioAttributes_l(request);
1167 }
1168 default:
1169 sp<MediaPlayerBase> p = getPlayer();
1170 if (p == 0) { return UNKNOWN_ERROR; }
1171 return p->setParameter(key, request);
1172 }
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001173}
1174
1175status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
Steve Block3856b092011-10-20 11:56:00 +01001176 ALOGV("[%d] getParameter(%d)", mConnId, key);
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001177 sp<MediaPlayerBase> p = getPlayer();
1178 if (p == 0) return UNKNOWN_ERROR;
1179 return p->getParameter(key, reply);
1180}
1181
John Grossmanc795b642012-02-22 15:38:35 -08001182status_t MediaPlayerService::Client::setRetransmitEndpoint(
1183 const struct sockaddr_in* endpoint) {
1184
1185 if (NULL != endpoint) {
1186 uint32_t a = ntohl(endpoint->sin_addr.s_addr);
1187 uint16_t p = ntohs(endpoint->sin_port);
1188 ALOGV("[%d] setRetransmitEndpoint(%u.%u.%u.%u:%hu)", mConnId,
1189 (a >> 24), (a >> 16) & 0xFF, (a >> 8) & 0xFF, (a & 0xFF), p);
1190 } else {
1191 ALOGV("[%d] setRetransmitEndpoint = <none>", mConnId);
1192 }
1193
1194 sp<MediaPlayerBase> p = getPlayer();
1195
1196 // Right now, the only valid time to set a retransmit endpoint is before
1197 // player selection has been made (since the presence or absence of a
1198 // retransmit endpoint is going to determine which player is selected during
1199 // setDataSource).
1200 if (p != 0) return INVALID_OPERATION;
1201
1202 if (NULL != endpoint) {
1203 mRetransmitEndpoint = *endpoint;
1204 mRetransmitEndpointValid = true;
1205 } else {
1206 mRetransmitEndpointValid = false;
1207 }
1208
1209 return NO_ERROR;
1210}
1211
John Grossman44a7e422012-06-21 17:29:24 -07001212status_t MediaPlayerService::Client::getRetransmitEndpoint(
1213 struct sockaddr_in* endpoint)
1214{
1215 if (NULL == endpoint)
1216 return BAD_VALUE;
1217
1218 sp<MediaPlayerBase> p = getPlayer();
1219
1220 if (p != NULL)
1221 return p->getRetransmitEndpoint(endpoint);
1222
1223 if (!mRetransmitEndpointValid)
1224 return NO_INIT;
1225
1226 *endpoint = mRetransmitEndpoint;
1227
1228 return NO_ERROR;
1229}
1230
Gloria Wangb483c472011-04-11 17:23:27 -07001231void MediaPlayerService::Client::notify(
1232 void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001233{
1234 Client* client = static_cast<Client*>(cookie);
James Dongb8a98252012-08-26 16:13:03 -07001235 if (client == NULL) {
1236 return;
1237 }
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001238
James Dongb8a98252012-08-26 16:13:03 -07001239 sp<IMediaPlayerClient> c;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001240 {
1241 Mutex::Autolock l(client->mLock);
James Dongb8a98252012-08-26 16:13:03 -07001242 c = client->mClient;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001243 if (msg == MEDIA_PLAYBACK_COMPLETE && client->mNextClient != NULL) {
John Grossmancb0b7552012-08-23 17:47:31 -07001244 if (client->mAudioOutput != NULL)
1245 client->mAudioOutput->switchToNextOutput();
Marco Nelissen6b74d672012-02-28 16:07:44 -08001246 client->mNextClient->start();
Wei Jia2afac0c2016-01-07 12:13:07 -08001247 if (client->mNextClient->mClient != NULL) {
1248 client->mNextClient->mClient->notify(
1249 MEDIA_INFO, MEDIA_INFO_STARTED_AS_NEXT, 0, obj);
1250 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001251 }
1252 }
1253
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001254 if (MEDIA_INFO == msg &&
Nicolas Catania48290382009-07-10 13:53:06 -07001255 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikoa64c8c72009-07-20 15:07:26 -07001256 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania48290382009-07-10 13:53:06 -07001257
1258 if(client->shouldDropMetadata(metadata_type)) {
1259 return;
1260 }
1261
1262 // Update the list of metadata that have changed. getMetadata
1263 // also access mMetadataUpdated and clears it.
1264 client->addNewMetadataUpdate(metadata_type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001265 }
James Dongb8a98252012-08-26 16:13:03 -07001266
1267 if (c != NULL) {
1268 ALOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
1269 c->notify(msg, ext1, ext2, obj);
1270 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001271}
1272
Nicolas Catania48290382009-07-10 13:53:06 -07001273
nikoa64c8c72009-07-20 15:07:26 -07001274bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001275{
Nicolas Catania48290382009-07-10 13:53:06 -07001276 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001277
Nicolas Catania48290382009-07-10 13:53:06 -07001278 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001279 return true;
1280 }
1281
Nicolas Catania48290382009-07-10 13:53:06 -07001282 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001283 return false;
Nicolas Catania48290382009-07-10 13:53:06 -07001284 } else {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001285 return true;
1286 }
1287}
1288
Nicolas Catania48290382009-07-10 13:53:06 -07001289
nikoa64c8c72009-07-20 15:07:26 -07001290void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania48290382009-07-10 13:53:06 -07001291 Mutex::Autolock lock(mLock);
1292 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1293 mMetadataUpdated.add(metadata_type);
1294 }
1295}
1296
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001297#if CALLBACK_ANTAGONIZER
1298const int Antagonizer::interval = 10000; // 10 msecs
1299
1300Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1301 mExit(false), mActive(false), mClient(client), mCb(cb)
1302{
1303 createThread(callbackThread, this);
1304}
1305
1306void Antagonizer::kill()
1307{
1308 Mutex::Autolock _l(mLock);
1309 mActive = false;
1310 mExit = true;
1311 mCondition.wait(mLock);
1312}
1313
1314int Antagonizer::callbackThread(void* user)
1315{
Steve Blockb8a80522011-12-20 16:23:08 +00001316 ALOGD("Antagonizer started");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001317 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1318 while (!p->mExit) {
1319 if (p->mActive) {
Steve Block3856b092011-10-20 11:56:00 +01001320 ALOGV("send event");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001321 p->mCb(p->mClient, 0, 0, 0);
1322 }
1323 usleep(interval);
1324 }
1325 Mutex::Autolock _l(p->mLock);
1326 p->mCondition.signal();
Steve Blockb8a80522011-12-20 16:23:08 +00001327 ALOGD("Antagonizer stopped");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001328 return 0;
1329}
1330#endif
1331
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001332#undef LOG_TAG
1333#define LOG_TAG "AudioSink"
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001334MediaPlayerService::AudioOutput::AudioOutput(int sessionId, int uid, int pid,
1335 const audio_attributes_t* attr)
Andreas Huber20111aa2009-07-14 16:56:47 -07001336 : mCallback(NULL),
Eric Laurenta514bdb2010-06-21 09:27:30 -07001337 mCallbackCookie(NULL),
Marco Nelissen6b74d672012-02-28 16:07:44 -08001338 mCallbackData(NULL),
Marco Nelissen4110c102012-03-29 09:31:28 -07001339 mBytesWritten(0),
Andy Hungd1c74342015-07-07 16:54:23 -07001340 mStreamType(AUDIO_STREAM_MUSIC),
Andy Hungd1c74342015-07-07 16:54:23 -07001341 mLeftVolume(1.0),
1342 mRightVolume(1.0),
1343 mPlaybackRate(AUDIO_PLAYBACK_RATE_DEFAULT),
1344 mSampleRateHz(0),
1345 mMsecsPerFrame(0),
1346 mFrameSize(0),
Eric Laurent1948eb32012-04-13 16:50:19 -07001347 mSessionId(sessionId),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001348 mUid(uid),
Marco Nelissend457c972014-02-11 08:47:07 -08001349 mPid(pid),
Andy Hungd1c74342015-07-07 16:54:23 -07001350 mSendLevel(0.0),
1351 mAuxEffectId(0),
1352 mFlags(AUDIO_OUTPUT_FLAG_NONE)
1353{
Steve Block3856b092011-10-20 11:56:00 +01001354 ALOGV("AudioOutput(%d)", sessionId);
Eric Laurent43562692015-07-15 16:49:07 -07001355 if (attr != NULL) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001356 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1357 if (mAttributes != NULL) {
1358 memcpy(mAttributes, attr, sizeof(audio_attributes_t));
1359 mStreamType = audio_attributes_to_stream_type(attr);
1360 }
1361 } else {
1362 mAttributes = NULL;
Eric Laurent43562692015-07-15 16:49:07 -07001363 }
1364
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001365 setMinBufferCount();
1366}
1367
1368MediaPlayerService::AudioOutput::~AudioOutput()
1369{
1370 close();
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001371 free(mAttributes);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001372 delete mCallbackData;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001373}
1374
Andy Hungd1c74342015-07-07 16:54:23 -07001375//static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001376void MediaPlayerService::AudioOutput::setMinBufferCount()
1377{
1378 char value[PROPERTY_VALUE_MAX];
1379 if (property_get("ro.kernel.qemu", value, 0)) {
1380 mIsOnEmulator = true;
1381 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1382 }
1383}
1384
Andy Hungd1c74342015-07-07 16:54:23 -07001385// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001386bool MediaPlayerService::AudioOutput::isOnEmulator()
1387{
Andy Hungd1c74342015-07-07 16:54:23 -07001388 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001389 return mIsOnEmulator;
1390}
1391
Andy Hungd1c74342015-07-07 16:54:23 -07001392// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001393int MediaPlayerService::AudioOutput::getMinBufferCount()
1394{
Andy Hungd1c74342015-07-07 16:54:23 -07001395 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001396 return mMinBufferCount;
1397}
1398
1399ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1400{
Andy Hungd1c74342015-07-07 16:54:23 -07001401 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001402 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001403 return mTrack->frameCount() * mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001404}
1405
1406ssize_t MediaPlayerService::AudioOutput::frameCount() const
1407{
Andy Hungd1c74342015-07-07 16:54:23 -07001408 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001409 if (mTrack == 0) return NO_INIT;
1410 return mTrack->frameCount();
1411}
1412
1413ssize_t MediaPlayerService::AudioOutput::channelCount() const
1414{
Andy Hungd1c74342015-07-07 16:54:23 -07001415 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001416 if (mTrack == 0) return NO_INIT;
1417 return mTrack->channelCount();
1418}
1419
1420ssize_t MediaPlayerService::AudioOutput::frameSize() const
1421{
Andy Hungd1c74342015-07-07 16:54:23 -07001422 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001423 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001424 return mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001425}
1426
1427uint32_t MediaPlayerService::AudioOutput::latency () const
1428{
Andy Hungd1c74342015-07-07 16:54:23 -07001429 Mutex::Autolock lock(mLock);
Eric Laurentdb354e52012-03-05 17:27:11 -08001430 if (mTrack == 0) return 0;
1431 return mTrack->latency();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001432}
1433
1434float MediaPlayerService::AudioOutput::msecsPerFrame() const
1435{
Andy Hungd1c74342015-07-07 16:54:23 -07001436 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001437 return mMsecsPerFrame;
1438}
1439
Marco Nelissen4110c102012-03-29 09:31:28 -07001440status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position) const
Eric Laurent342e9cf2010-01-19 17:37:09 -08001441{
Andy Hungd1c74342015-07-07 16:54:23 -07001442 Mutex::Autolock lock(mLock);
Eric Laurent342e9cf2010-01-19 17:37:09 -08001443 if (mTrack == 0) return NO_INIT;
1444 return mTrack->getPosition(position);
1445}
1446
Lajos Molnar06ad1522014-08-28 07:27:44 -07001447status_t MediaPlayerService::AudioOutput::getTimestamp(AudioTimestamp &ts) const
1448{
Andy Hungd1c74342015-07-07 16:54:23 -07001449 Mutex::Autolock lock(mLock);
Lajos Molnar06ad1522014-08-28 07:27:44 -07001450 if (mTrack == 0) return NO_INIT;
1451 return mTrack->getTimestamp(ts);
1452}
1453
Wei Jiac4ac8172015-10-21 10:35:48 -07001454// TODO: Remove unnecessary calls to getPlayedOutDurationUs()
1455// as it acquires locks and may query the audio driver.
1456//
1457// Some calls could conceivably retrieve extrapolated data instead of
1458// accessing getTimestamp() or getPosition() every time a data buffer with
1459// a media time is received.
1460//
1461// Calculate duration of played samples if played at normal rate (i.e., 1.0).
1462int64_t MediaPlayerService::AudioOutput::getPlayedOutDurationUs(int64_t nowUs) const
1463{
1464 Mutex::Autolock lock(mLock);
1465 if (mTrack == 0 || mSampleRateHz == 0) {
Wei Jia213f4902015-10-22 08:55:25 -07001466 return 0;
Wei Jiac4ac8172015-10-21 10:35:48 -07001467 }
1468
1469 uint32_t numFramesPlayed;
1470 int64_t numFramesPlayedAt;
1471 AudioTimestamp ts;
1472 static const int64_t kStaleTimestamp100ms = 100000;
1473
1474 status_t res = mTrack->getTimestamp(ts);
1475 if (res == OK) { // case 1: mixing audio tracks and offloaded tracks.
1476 numFramesPlayed = ts.mPosition;
1477 numFramesPlayedAt = ts.mTime.tv_sec * 1000000LL + ts.mTime.tv_nsec / 1000;
1478 const int64_t timestampAge = nowUs - numFramesPlayedAt;
1479 if (timestampAge > kStaleTimestamp100ms) {
1480 // This is an audio FIXME.
1481 // getTimestamp returns a timestamp which may come from audio mixing threads.
1482 // After pausing, the MixerThread may go idle, thus the mTime estimate may
1483 // become stale. Assuming that the MixerThread runs 20ms, with FastMixer at 5ms,
1484 // the max latency should be about 25ms with an average around 12ms (to be verified).
1485 // For safety we use 100ms.
1486 ALOGV("getTimestamp: returned stale timestamp nowUs(%lld) numFramesPlayedAt(%lld)",
1487 (long long)nowUs, (long long)numFramesPlayedAt);
1488 numFramesPlayedAt = nowUs - kStaleTimestamp100ms;
1489 }
1490 //ALOGD("getTimestamp: OK %d %lld", numFramesPlayed, (long long)numFramesPlayedAt);
1491 } else if (res == WOULD_BLOCK) { // case 2: transitory state on start of a new track
1492 numFramesPlayed = 0;
1493 numFramesPlayedAt = nowUs;
1494 //ALOGD("getTimestamp: WOULD_BLOCK %d %lld",
1495 // numFramesPlayed, (long long)numFramesPlayedAt);
1496 } else { // case 3: transitory at new track or audio fast tracks.
1497 res = mTrack->getPosition(&numFramesPlayed);
1498 CHECK_EQ(res, (status_t)OK);
1499 numFramesPlayedAt = nowUs;
1500 numFramesPlayedAt += 1000LL * mTrack->latency() / 2; /* XXX */
1501 //ALOGD("getPosition: %u %lld", numFramesPlayed, (long long)numFramesPlayedAt);
1502 }
1503
1504 // CHECK_EQ(numFramesPlayed & (1 << 31), 0); // can't be negative until 12.4 hrs, test
1505 // TODO: remove the (int32_t) casting below as it may overflow at 12.4 hours.
1506 int64_t durationUs = (int64_t)((int32_t)numFramesPlayed * 1000000LL / mSampleRateHz)
1507 + nowUs - numFramesPlayedAt;
1508 if (durationUs < 0) {
1509 // Occurs when numFramesPlayed position is very small and the following:
1510 // (1) In case 1, the time nowUs is computed before getTimestamp() is called and
1511 // numFramesPlayedAt is greater than nowUs by time more than numFramesPlayed.
1512 // (2) In case 3, using getPosition and adding mAudioSink->latency() to
1513 // numFramesPlayedAt, by a time amount greater than numFramesPlayed.
1514 //
1515 // Both of these are transitory conditions.
1516 ALOGV("getPlayedOutDurationUs: negative duration %lld set to zero", (long long)durationUs);
1517 durationUs = 0;
1518 }
1519 ALOGV("getPlayedOutDurationUs(%lld) nowUs(%lld) frames(%u) framesAt(%lld)",
1520 (long long)durationUs, (long long)nowUs, numFramesPlayed, (long long)numFramesPlayedAt);
1521 return durationUs;
1522}
1523
Marco Nelissen4110c102012-03-29 09:31:28 -07001524status_t MediaPlayerService::AudioOutput::getFramesWritten(uint32_t *frameswritten) const
1525{
Andy Hungd1c74342015-07-07 16:54:23 -07001526 Mutex::Autolock lock(mLock);
Marco Nelissen4110c102012-03-29 09:31:28 -07001527 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001528 *frameswritten = mBytesWritten / mFrameSize;
Marco Nelissen4110c102012-03-29 09:31:28 -07001529 return OK;
1530}
1531
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001532status_t MediaPlayerService::AudioOutput::setParameters(const String8& keyValuePairs)
1533{
Andy Hungd1c74342015-07-07 16:54:23 -07001534 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001535 if (mTrack == 0) return NO_INIT;
1536 return mTrack->setParameters(keyValuePairs);
1537}
1538
1539String8 MediaPlayerService::AudioOutput::getParameters(const String8& keys)
1540{
Andy Hungd1c74342015-07-07 16:54:23 -07001541 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001542 if (mTrack == 0) return String8::empty();
1543 return mTrack->getParameters(keys);
1544}
1545
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001546void MediaPlayerService::AudioOutput::setAudioAttributes(const audio_attributes_t * attributes) {
Andy Hungd1c74342015-07-07 16:54:23 -07001547 Mutex::Autolock lock(mLock);
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001548 if (attributes == NULL) {
1549 free(mAttributes);
1550 mAttributes = NULL;
1551 } else {
1552 if (mAttributes == NULL) {
1553 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1554 }
1555 memcpy(mAttributes, attributes, sizeof(audio_attributes_t));
Eric Laurent43562692015-07-15 16:49:07 -07001556 mStreamType = audio_attributes_to_stream_type(attributes);
1557 }
1558}
1559
1560void MediaPlayerService::AudioOutput::setAudioStreamType(audio_stream_type_t streamType)
1561{
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001562 Mutex::Autolock lock(mLock);
Eric Laurent43562692015-07-15 16:49:07 -07001563 // do not allow direct stream type modification if attributes have been set
1564 if (mAttributes == NULL) {
1565 mStreamType = streamType;
1566 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001567}
1568
Andy Hungd1c74342015-07-07 16:54:23 -07001569void MediaPlayerService::AudioOutput::deleteRecycledTrack_l()
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001570{
Andy Hungd1c74342015-07-07 16:54:23 -07001571 ALOGV("deleteRecycledTrack_l");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001572 if (mRecycledTrack != 0) {
1573
1574 if (mCallbackData != NULL) {
1575 mCallbackData->setOutput(NULL);
1576 mCallbackData->endTrackSwitch();
1577 }
1578
1579 if ((mRecycledTrack->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) {
1580 mRecycledTrack->flush();
1581 }
1582 // An offloaded track isn't flushed because the STREAM_END is reported
1583 // slightly prematurely to allow time for the gapless track switch
1584 // but this means that if we decide not to recycle the track there
1585 // could be a small amount of residual data still playing. We leave
1586 // AudioFlinger to drain the track.
1587
1588 mRecycledTrack.clear();
Andy Hungd1c74342015-07-07 16:54:23 -07001589 close_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001590 delete mCallbackData;
1591 mCallbackData = NULL;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001592 }
1593}
1594
Andy Hungd1c74342015-07-07 16:54:23 -07001595void MediaPlayerService::AudioOutput::close_l()
1596{
1597 mTrack.clear();
1598}
1599
Andreas Huber20111aa2009-07-14 16:56:47 -07001600status_t MediaPlayerService::AudioOutput::open(
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001601 uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
1602 audio_format_t format, int bufferCount,
Eric Laurent1948eb32012-04-13 16:50:19 -07001603 AudioCallback cb, void *cookie,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001604 audio_output_flags_t flags,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001605 const audio_offload_info_t *offloadInfo,
Andy Hung179652e2015-05-31 22:49:46 -07001606 bool doNotReconnect,
1607 uint32_t suggestedFrameCount)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001608{
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001609 ALOGV("open(%u, %d, 0x%x, 0x%x, %d, %d 0x%x)", sampleRate, channelCount, channelMask,
1610 format, bufferCount, mSessionId, flags);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001611
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001612 // offloading is only supported in callback mode for now.
1613 // offloadInfo must be present if offload flag is set
1614 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) &&
1615 ((cb == NULL) || (offloadInfo == NULL))) {
1616 return BAD_VALUE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001617 }
1618
Andy Hung179652e2015-05-31 22:49:46 -07001619 // compute frame count for the AudioTrack internal buffer
1620 size_t frameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001621 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1622 frameCount = 0; // AudioTrack will get frame count from AudioFlinger
1623 } else {
Andy Hung179652e2015-05-31 22:49:46 -07001624 // try to estimate the buffer processing fetch size from AudioFlinger.
1625 // framesPerBuffer is approximate and generally correct, except when it's not :-).
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001626 uint32_t afSampleRate;
1627 size_t afFrameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001628 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1629 return NO_INIT;
1630 }
1631 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1632 return NO_INIT;
1633 }
Andy Hung179652e2015-05-31 22:49:46 -07001634 const size_t framesPerBuffer =
1635 (unsigned long long)sampleRate * afFrameCount / afSampleRate;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001636
Andy Hung179652e2015-05-31 22:49:46 -07001637 if (bufferCount == 0) {
1638 // use suggestedFrameCount
1639 bufferCount = (suggestedFrameCount + framesPerBuffer - 1) / framesPerBuffer;
1640 }
1641 // Check argument bufferCount against the mininum buffer count
1642 if (bufferCount != 0 && bufferCount < mMinBufferCount) {
1643 ALOGV("bufferCount (%d) increased to %d", bufferCount, mMinBufferCount);
1644 bufferCount = mMinBufferCount;
1645 }
1646 // if frameCount is 0, then AudioTrack will get frame count from AudioFlinger
1647 // which will be the minimum size permitted.
1648 frameCount = bufferCount * framesPerBuffer;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001649 }
Andreas Huber20111aa2009-07-14 16:56:47 -07001650
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001651 if (channelMask == CHANNEL_MASK_USE_CHANNEL_ORDER) {
Glenn Kastenab334fd2012-03-14 12:56:06 -07001652 channelMask = audio_channel_out_mask_from_count(channelCount);
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001653 if (0 == channelMask) {
1654 ALOGE("open() error, can\'t derive mask for %d audio channels", channelCount);
1655 return NO_INIT;
1656 }
1657 }
Eric Laurent1948eb32012-04-13 16:50:19 -07001658
Andy Hungd1c74342015-07-07 16:54:23 -07001659 Mutex::Autolock lock(mLock);
Andy Hung179652e2015-05-31 22:49:46 -07001660 mCallback = cb;
1661 mCallbackCookie = cookie;
1662
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001663 // Check whether we can recycle the track
1664 bool reuse = false;
1665 bool bothOffloaded = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001666
Glenn Kasten2799d742013-05-30 14:33:29 -07001667 if (mRecycledTrack != 0) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001668 // check whether we are switching between two offloaded tracks
1669 bothOffloaded = (flags & mRecycledTrack->getFlags()
1670 & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0;
Marco Nelissen67295b52012-06-11 14:52:53 -07001671
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001672 // check if the existing track can be reused as-is, or if a new track needs to be created.
1673 reuse = true;
1674
Marco Nelissen67295b52012-06-11 14:52:53 -07001675 if ((mCallbackData == NULL && mCallback != NULL) ||
1676 (mCallbackData != NULL && mCallback == NULL)) {
1677 // recycled track uses callbacks but the caller wants to use writes, or vice versa
1678 ALOGV("can't chain callback and write");
1679 reuse = false;
1680 } else if ((mRecycledTrack->getSampleRate() != sampleRate) ||
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001681 (mRecycledTrack->channelCount() != (uint32_t)channelCount) ) {
1682 ALOGV("samplerate, channelcount differ: %u/%u Hz, %u/%d ch",
Marco Nelissen67295b52012-06-11 14:52:53 -07001683 mRecycledTrack->getSampleRate(), sampleRate,
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001684 mRecycledTrack->channelCount(), channelCount);
Marco Nelissen67295b52012-06-11 14:52:53 -07001685 reuse = false;
1686 } else if (flags != mFlags) {
1687 ALOGV("output flags differ %08x/%08x", flags, mFlags);
1688 reuse = false;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001689 } else if (mRecycledTrack->format() != format) {
1690 reuse = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001691 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001692 } else {
1693 ALOGV("no track available to recycle");
1694 }
1695
1696 ALOGV_IF(bothOffloaded, "both tracks offloaded");
1697
1698 // If we can't recycle and both tracks are offloaded
1699 // we must close the previous output before opening a new one
1700 if (bothOffloaded && !reuse) {
1701 ALOGV("both offloaded and not recycling");
Andy Hungd1c74342015-07-07 16:54:23 -07001702 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001703 }
1704
1705 sp<AudioTrack> t;
1706 CallbackData *newcbd = NULL;
1707
1708 // We don't attempt to create a new track if we are recycling an
1709 // offloaded track. But, if we are recycling a non-offloaded or we
1710 // are switching where one is offloaded and one isn't then we create
1711 // the new track in advance so that we can read additional stream info
1712
1713 if (!(reuse && bothOffloaded)) {
1714 ALOGV("creating new AudioTrack");
1715
1716 if (mCallback != NULL) {
1717 newcbd = new CallbackData(this);
1718 t = new AudioTrack(
1719 mStreamType,
1720 sampleRate,
1721 format,
1722 channelMask,
1723 frameCount,
1724 flags,
1725 CallbackWrapper,
1726 newcbd,
1727 0, // notification frames
1728 mSessionId,
1729 AudioTrack::TRANSFER_CALLBACK,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001730 offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -08001731 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001732 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001733 mAttributes,
1734 doNotReconnect);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001735 } else {
1736 t = new AudioTrack(
1737 mStreamType,
1738 sampleRate,
1739 format,
1740 channelMask,
1741 frameCount,
1742 flags,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001743 NULL, // callback
1744 NULL, // user data
1745 0, // notification frames
1746 mSessionId,
1747 AudioTrack::TRANSFER_DEFAULT,
1748 NULL, // offload info
Marco Nelissend457c972014-02-11 08:47:07 -08001749 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001750 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001751 mAttributes,
1752 doNotReconnect);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001753 }
1754
1755 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1756 ALOGE("Unable to create audio track");
1757 delete newcbd;
Glenn Kasten3e98ecd2015-05-18 13:13:24 -07001758 // t goes out of scope, so reference count drops to zero
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001759 return NO_INIT;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001760 } else {
1761 // successful AudioTrack initialization implies a legacy stream type was generated
1762 // from the audio attributes
1763 mStreamType = t->streamType();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001764 }
1765 }
1766
1767 if (reuse) {
1768 CHECK(mRecycledTrack != NULL);
1769
1770 if (!bothOffloaded) {
1771 if (mRecycledTrack->frameCount() != t->frameCount()) {
1772 ALOGV("framecount differs: %u/%u frames",
1773 mRecycledTrack->frameCount(), t->frameCount());
1774 reuse = false;
1775 }
1776 }
1777
Marco Nelissen67295b52012-06-11 14:52:53 -07001778 if (reuse) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001779 ALOGV("chaining to next output and recycling track");
Andy Hungd1c74342015-07-07 16:54:23 -07001780 close_l();
Marco Nelissen67295b52012-06-11 14:52:53 -07001781 mTrack = mRecycledTrack;
Glenn Kasten2799d742013-05-30 14:33:29 -07001782 mRecycledTrack.clear();
Marco Nelissen67295b52012-06-11 14:52:53 -07001783 if (mCallbackData != NULL) {
1784 mCallbackData->setOutput(this);
1785 }
Marco Nelissen67295b52012-06-11 14:52:53 -07001786 delete newcbd;
1787 return OK;
1788 }
Marco Nelissen67295b52012-06-11 14:52:53 -07001789 }
1790
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001791 // we're not going to reuse the track, unblock and flush it
1792 // this was done earlier if both tracks are offloaded
1793 if (!bothOffloaded) {
Andy Hungd1c74342015-07-07 16:54:23 -07001794 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001795 }
1796
1797 CHECK((t != NULL) && ((mCallback == NULL) || (newcbd != NULL)));
1798
Marco Nelissen67295b52012-06-11 14:52:53 -07001799 mCallbackData = newcbd;
Steve Block3856b092011-10-20 11:56:00 +01001800 ALOGV("setVolume");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001801 t->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07001802
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001803 mSampleRateHz = sampleRate;
Preetam Singh Ranawat2e17eef2015-08-12 12:11:46 -07001804 mFlags = flags;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001805 mMsecsPerFrame = 1E3f / (mPlaybackRate.mSpeed * sampleRate);
Andy Hungd1c74342015-07-07 16:54:23 -07001806 mFrameSize = t->frameSize();
Marco Nelissen99448602012-04-02 12:16:49 -07001807 uint32_t pos;
1808 if (t->getPosition(&pos) == OK) {
Andy Hungd1c74342015-07-07 16:54:23 -07001809 mBytesWritten = uint64_t(pos) * mFrameSize;
Marco Nelissen99448602012-04-02 12:16:49 -07001810 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001811 mTrack = t;
Eric Laurent2beeb502010-07-16 07:43:46 -07001812
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001813 status_t res = NO_ERROR;
Wei Jia0162d002015-06-09 11:59:33 -07001814 // Note some output devices may give us a direct track even though we don't specify it.
1815 // Example: Line application b/17459982.
Preetam Singh Ranawat2e17eef2015-08-12 12:11:46 -07001816 if ((t->getFlags() & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) {
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001817 res = t->setPlaybackRate(mPlaybackRate);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001818 if (res == NO_ERROR) {
1819 t->setAuxEffectSendLevel(mSendLevel);
1820 res = t->attachAuxEffect(mAuxEffectId);
1821 }
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001822 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001823 ALOGV("open() DONE status %d", res);
1824 return res;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001825}
1826
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001827status_t MediaPlayerService::AudioOutput::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001828{
Steve Block3856b092011-10-20 11:56:00 +01001829 ALOGV("start");
Andy Hungd1c74342015-07-07 16:54:23 -07001830 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001831 if (mCallbackData != NULL) {
1832 mCallbackData->endTrackSwitch();
1833 }
Glenn Kasten2799d742013-05-30 14:33:29 -07001834 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001835 mTrack->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07001836 mTrack->setAuxEffectSendLevel(mSendLevel);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001837 return mTrack->start();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001838 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001839 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001840}
1841
Marco Nelissen6b74d672012-02-28 16:07:44 -08001842void MediaPlayerService::AudioOutput::setNextOutput(const sp<AudioOutput>& nextOutput) {
Andy Hungd1c74342015-07-07 16:54:23 -07001843 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001844 mNextOutput = nextOutput;
1845}
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08001846
Marco Nelissen6b74d672012-02-28 16:07:44 -08001847void MediaPlayerService::AudioOutput::switchToNextOutput() {
1848 ALOGV("switchToNextOutput");
Andy Hungd1c74342015-07-07 16:54:23 -07001849
1850 // Try to acquire the callback lock before moving track (without incurring deadlock).
1851 const unsigned kMaxSwitchTries = 100;
1852 Mutex::Autolock lock(mLock);
1853 for (unsigned tries = 0;;) {
1854 if (mTrack == 0) {
1855 return;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001856 }
Andy Hungd1c74342015-07-07 16:54:23 -07001857 if (mNextOutput != NULL && mNextOutput != this) {
1858 if (mCallbackData != NULL) {
1859 // two alternative approaches
1860#if 1
1861 CallbackData *callbackData = mCallbackData;
1862 mLock.unlock();
1863 // proper acquisition sequence
1864 callbackData->lock();
1865 mLock.lock();
1866 // Caution: it is unlikely that someone deleted our callback or changed our target
1867 if (callbackData != mCallbackData || mNextOutput == NULL || mNextOutput == this) {
1868 // fatal if we are starved out.
1869 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
1870 "switchToNextOutput() cannot obtain correct lock sequence");
1871 callbackData->unlock();
1872 continue;
1873 }
1874 callbackData->mSwitching = true; // begin track switch
1875#else
1876 // tryBeginTrackSwitch() returns false if the callback has the lock.
1877 if (!mCallbackData->tryBeginTrackSwitch()) {
1878 // fatal if we are starved out.
1879 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
1880 "switchToNextOutput() cannot obtain callback lock");
1881 mLock.unlock();
1882 usleep(5 * 1000 /* usec */); // allow callback to use AudioOutput
1883 mLock.lock();
1884 continue;
1885 }
1886#endif
1887 }
1888
1889 Mutex::Autolock nextLock(mNextOutput->mLock);
1890
1891 // If the next output track is not NULL, then it has been
1892 // opened already for playback.
1893 // This is possible even without the next player being started,
1894 // for example, the next player could be prepared and seeked.
1895 //
1896 // Presuming it isn't advisable to force the track over.
1897 if (mNextOutput->mTrack == NULL) {
1898 ALOGD("Recycling track for gapless playback");
1899 delete mNextOutput->mCallbackData;
1900 mNextOutput->mCallbackData = mCallbackData;
1901 mNextOutput->mRecycledTrack = mTrack;
1902 mNextOutput->mSampleRateHz = mSampleRateHz;
1903 mNextOutput->mMsecsPerFrame = mMsecsPerFrame;
1904 mNextOutput->mBytesWritten = mBytesWritten;
1905 mNextOutput->mFlags = mFlags;
1906 mNextOutput->mFrameSize = mFrameSize;
1907 close_l();
1908 mCallbackData = NULL; // destruction handled by mNextOutput
1909 } else {
1910 ALOGW("Ignoring gapless playback because next player has already started");
1911 // remove track in case resource needed for future players.
1912 if (mCallbackData != NULL) {
1913 mCallbackData->endTrackSwitch(); // release lock for callbacks before close.
1914 }
1915 close_l();
1916 }
1917 }
1918 break;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001919 }
1920}
1921
Wei Jia7d3f4df2015-03-03 15:28:00 -08001922ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001923{
Andy Hungd1c74342015-07-07 16:54:23 -07001924 Mutex::Autolock lock(mLock);
Glenn Kastenadad3d72014-02-21 14:51:43 -08001925 LOG_ALWAYS_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
Andreas Huber20111aa2009-07-14 16:56:47 -07001926
Steve Block3856b092011-10-20 11:56:00 +01001927 //ALOGV("write(%p, %u)", buffer, size);
Glenn Kasten2799d742013-05-30 14:33:29 -07001928 if (mTrack != 0) {
Wei Jia7d3f4df2015-03-03 15:28:00 -08001929 ssize_t ret = mTrack->write(buffer, size, blocking);
Andy Hunga31335a2014-08-20 17:37:59 -07001930 if (ret >= 0) {
1931 mBytesWritten += ret;
1932 }
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001933 return ret;
1934 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001935 return NO_INIT;
1936}
1937
1938void MediaPlayerService::AudioOutput::stop()
1939{
Steve Block3856b092011-10-20 11:56:00 +01001940 ALOGV("stop");
Andy Hungd1c74342015-07-07 16:54:23 -07001941 Mutex::Autolock lock(mLock);
Andy Hungda17c042015-06-01 15:53:14 -07001942 mBytesWritten = 0;
Glenn Kasten2799d742013-05-30 14:33:29 -07001943 if (mTrack != 0) mTrack->stop();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001944}
1945
1946void MediaPlayerService::AudioOutput::flush()
1947{
Steve Block3856b092011-10-20 11:56:00 +01001948 ALOGV("flush");
Andy Hungd1c74342015-07-07 16:54:23 -07001949 Mutex::Autolock lock(mLock);
Andy Hungda17c042015-06-01 15:53:14 -07001950 mBytesWritten = 0;
Glenn Kasten2799d742013-05-30 14:33:29 -07001951 if (mTrack != 0) mTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001952}
1953
1954void MediaPlayerService::AudioOutput::pause()
1955{
Steve Block3856b092011-10-20 11:56:00 +01001956 ALOGV("pause");
Andy Hungd1c74342015-07-07 16:54:23 -07001957 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07001958 if (mTrack != 0) mTrack->pause();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001959}
1960
1961void MediaPlayerService::AudioOutput::close()
1962{
Steve Block3856b092011-10-20 11:56:00 +01001963 ALOGV("close");
Erik Wolsheimer7845a1f2015-10-30 12:07:52 -07001964 sp<AudioTrack> track;
1965 {
1966 Mutex::Autolock lock(mLock);
1967 track = mTrack;
1968 close_l(); // clears mTrack
1969 }
1970 // destruction of the track occurs outside of mutex.
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001971}
1972
1973void MediaPlayerService::AudioOutput::setVolume(float left, float right)
1974{
Steve Block3856b092011-10-20 11:56:00 +01001975 ALOGV("setVolume(%f, %f)", left, right);
Andy Hungd1c74342015-07-07 16:54:23 -07001976 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001977 mLeftVolume = left;
1978 mRightVolume = right;
Glenn Kasten2799d742013-05-30 14:33:29 -07001979 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001980 mTrack->setVolume(left, right);
1981 }
1982}
1983
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001984status_t MediaPlayerService::AudioOutput::setPlaybackRate(const AudioPlaybackRate &rate)
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001985{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001986 ALOGV("setPlaybackRate(%f %f %d %d)",
1987 rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Andy Hungd1c74342015-07-07 16:54:23 -07001988 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001989 if (mTrack == 0) {
1990 // remember rate so that we can set it when the track is opened
1991 mPlaybackRate = rate;
1992 return OK;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001993 }
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001994 status_t res = mTrack->setPlaybackRate(rate);
1995 if (res != NO_ERROR) {
1996 return res;
1997 }
1998 // rate.mSpeed is always greater than 0 if setPlaybackRate succeeded
1999 CHECK_GT(rate.mSpeed, 0.f);
2000 mPlaybackRate = rate;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002001 if (mSampleRateHz != 0) {
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002002 mMsecsPerFrame = 1E3f / (rate.mSpeed * mSampleRateHz);
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002003 }
2004 return res;
2005}
2006
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002007status_t MediaPlayerService::AudioOutput::getPlaybackRate(AudioPlaybackRate *rate)
2008{
2009 ALOGV("setPlaybackRate");
Andy Hungd1c74342015-07-07 16:54:23 -07002010 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002011 if (mTrack == 0) {
2012 return NO_INIT;
2013 }
2014 *rate = mTrack->getPlaybackRate();
2015 return NO_ERROR;
2016}
2017
Eric Laurent2beeb502010-07-16 07:43:46 -07002018status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
2019{
Steve Block3856b092011-10-20 11:56:00 +01002020 ALOGV("setAuxEffectSendLevel(%f)", level);
Andy Hungd1c74342015-07-07 16:54:23 -07002021 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002022 mSendLevel = level;
Glenn Kasten2799d742013-05-30 14:33:29 -07002023 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002024 return mTrack->setAuxEffectSendLevel(level);
2025 }
2026 return NO_ERROR;
2027}
2028
2029status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
2030{
Steve Block3856b092011-10-20 11:56:00 +01002031 ALOGV("attachAuxEffect(%d)", effectId);
Andy Hungd1c74342015-07-07 16:54:23 -07002032 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002033 mAuxEffectId = effectId;
Glenn Kasten2799d742013-05-30 14:33:29 -07002034 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002035 return mTrack->attachAuxEffect(effectId);
2036 }
2037 return NO_ERROR;
2038}
2039
Andreas Huber20111aa2009-07-14 16:56:47 -07002040// static
2041void MediaPlayerService::AudioOutput::CallbackWrapper(
Glenn Kastend217a8c2011-06-01 15:20:35 -07002042 int event, void *cookie, void *info) {
Steve Block3856b092011-10-20 11:56:00 +01002043 //ALOGV("callbackwrapper");
Marco Nelissen6b74d672012-02-28 16:07:44 -08002044 CallbackData *data = (CallbackData*)cookie;
Andy Hungd1c74342015-07-07 16:54:23 -07002045 // lock to ensure we aren't caught in the middle of a track switch.
Marco Nelissen6b74d672012-02-28 16:07:44 -08002046 data->lock();
2047 AudioOutput *me = data->getOutput();
Andreas Huber20111aa2009-07-14 16:56:47 -07002048 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002049 if (me == NULL) {
2050 // no output set, likely because the track was scheduled to be reused
2051 // by another player, but the format turned out to be incompatible.
2052 data->unlock();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002053 if (buffer != NULL) {
2054 buffer->size = 0;
2055 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08002056 return;
2057 }
Andreas Huber20111aa2009-07-14 16:56:47 -07002058
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002059 switch(event) {
2060 case AudioTrack::EVENT_MORE_DATA: {
2061 size_t actualSize = (*me->mCallback)(
2062 me, buffer->raw, buffer->size, me->mCallbackCookie,
2063 CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002064
Andy Hung719b46b2015-05-31 22:18:25 -07002065 // Log when no data is returned from the callback.
2066 // (1) We may have no data (especially with network streaming sources).
2067 // (2) We may have reached the EOS and the audio track is not stopped yet.
2068 // Note that AwesomePlayer/AudioPlayer will only return zero size when it reaches the EOS.
2069 // NuPlayerRenderer will return zero when it doesn't have data (it doesn't block to fill).
2070 //
2071 // This is a benign busy-wait, with the next data request generated 10 ms or more later;
2072 // nevertheless for power reasons, we don't want to see too many of these.
Andreas Huber2e8ffaf2010-02-18 16:45:13 -08002073
Andy Hung719b46b2015-05-31 22:18:25 -07002074 ALOGV_IF(actualSize == 0 && buffer->size > 0, "callbackwrapper: empty buffer returned");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002075
Andy Hung719b46b2015-05-31 22:18:25 -07002076 me->mBytesWritten += actualSize; // benign race with reader.
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002077 buffer->size = actualSize;
2078 } break;
2079
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002080 case AudioTrack::EVENT_STREAM_END:
Andy Hung719b46b2015-05-31 22:18:25 -07002081 // currently only occurs for offloaded callbacks
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002082 ALOGV("callbackwrapper: deliver EVENT_STREAM_END");
2083 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2084 me->mCallbackCookie, CB_EVENT_STREAM_END);
2085 break;
2086
2087 case AudioTrack::EVENT_NEW_IAUDIOTRACK :
2088 ALOGV("callbackwrapper: deliver EVENT_TEAR_DOWN");
2089 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2090 me->mCallbackCookie, CB_EVENT_TEAR_DOWN);
2091 break;
2092
Glenn Kasten421743b2015-06-01 08:18:08 -07002093 case AudioTrack::EVENT_UNDERRUN:
Andy Hung719b46b2015-05-31 22:18:25 -07002094 // This occurs when there is no data available, typically
Glenn Kasten421743b2015-06-01 08:18:08 -07002095 // when there is a failure to supply data to the AudioTrack. It can also
2096 // occur in non-offloaded mode when the audio device comes out of standby.
2097 //
Andy Hung719b46b2015-05-31 22:18:25 -07002098 // If an AudioTrack underruns it outputs silence. Since this happens suddenly
2099 // it may sound like an audible pop or glitch.
2100 //
2101 // The underrun event is sent once per track underrun; the condition is reset
2102 // when more data is sent to the AudioTrack.
Glenn Kasten421743b2015-06-01 08:18:08 -07002103 ALOGI("callbackwrapper: EVENT_UNDERRUN (discarded)");
2104 break;
2105
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002106 default:
2107 ALOGE("received unknown event type: %d inside CallbackWrapper !", event);
Andreas Huber51c1e0e2011-04-04 11:43:40 -07002108 }
2109
Marco Nelissen6b74d672012-02-28 16:07:44 -08002110 data->unlock();
Andreas Huber20111aa2009-07-14 16:56:47 -07002111}
2112
Marco Nelissen4110c102012-03-29 09:31:28 -07002113int MediaPlayerService::AudioOutput::getSessionId() const
Eric Laurent8c563ed2010-10-07 18:23:03 -07002114{
Andy Hungd1c74342015-07-07 16:54:23 -07002115 Mutex::Autolock lock(mLock);
Eric Laurent8c563ed2010-10-07 18:23:03 -07002116 return mSessionId;
2117}
2118
Eric Laurent6f59db12013-07-26 17:16:50 -07002119uint32_t MediaPlayerService::AudioOutput::getSampleRate() const
2120{
Andy Hungd1c74342015-07-07 16:54:23 -07002121 Mutex::Autolock lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -07002122 if (mTrack == 0) return 0;
2123 return mTrack->getSampleRate();
2124}
2125
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002126////////////////////////////////////////////////////////////////////////////////
2127
2128struct CallbackThread : public Thread {
2129 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
2130 MediaPlayerBase::AudioSink::AudioCallback cb,
2131 void *cookie);
2132
2133protected:
2134 virtual ~CallbackThread();
2135
2136 virtual bool threadLoop();
2137
2138private:
2139 wp<MediaPlayerBase::AudioSink> mSink;
2140 MediaPlayerBase::AudioSink::AudioCallback mCallback;
2141 void *mCookie;
2142 void *mBuffer;
2143 size_t mBufferSize;
2144
2145 CallbackThread(const CallbackThread &);
2146 CallbackThread &operator=(const CallbackThread &);
2147};
2148
2149CallbackThread::CallbackThread(
2150 const wp<MediaPlayerBase::AudioSink> &sink,
2151 MediaPlayerBase::AudioSink::AudioCallback cb,
2152 void *cookie)
2153 : mSink(sink),
2154 mCallback(cb),
2155 mCookie(cookie),
2156 mBuffer(NULL),
2157 mBufferSize(0) {
2158}
2159
2160CallbackThread::~CallbackThread() {
2161 if (mBuffer) {
2162 free(mBuffer);
2163 mBuffer = NULL;
2164 }
2165}
2166
2167bool CallbackThread::threadLoop() {
2168 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
2169 if (sink == NULL) {
2170 return false;
2171 }
2172
2173 if (mBuffer == NULL) {
2174 mBufferSize = sink->bufferSize();
2175 mBuffer = malloc(mBufferSize);
2176 }
2177
2178 size_t actualSize =
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002179 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie,
2180 MediaPlayerBase::AudioSink::CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002181
2182 if (actualSize > 0) {
2183 sink->write(mBuffer, actualSize);
Andy Hunga31335a2014-08-20 17:37:59 -07002184 // Could return false on sink->write() error or short count.
2185 // Not necessarily appropriate but would work for AudioCache behavior.
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002186 }
2187
2188 return true;
2189}
2190
2191////////////////////////////////////////////////////////////////////////////////
2192
Gloria Wang7cf180c2011-02-19 18:37:57 -08002193void MediaPlayerService::addBatteryData(uint32_t params)
2194{
2195 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002196
2197 int32_t time = systemTime() / 1000000L;
2198
2199 // change audio output devices. This notification comes from AudioFlinger
2200 if ((params & kBatteryDataSpeakerOn)
2201 || (params & kBatteryDataOtherAudioDeviceOn)) {
2202
2203 int deviceOn[NUM_AUDIO_DEVICES];
2204 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2205 deviceOn[i] = 0;
2206 }
2207
2208 if ((params & kBatteryDataSpeakerOn)
2209 && (params & kBatteryDataOtherAudioDeviceOn)) {
2210 deviceOn[SPEAKER_AND_OTHER] = 1;
2211 } else if (params & kBatteryDataSpeakerOn) {
2212 deviceOn[SPEAKER] = 1;
2213 } else {
2214 deviceOn[OTHER_AUDIO_DEVICE] = 1;
2215 }
2216
2217 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2218 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
2219
2220 if (mBatteryAudio.refCount > 0) { // if playing audio
2221 if (!deviceOn[i]) {
2222 mBatteryAudio.lastTime[i] += time;
2223 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2224 mBatteryAudio.lastTime[i] = 0;
2225 } else {
2226 mBatteryAudio.lastTime[i] = 0 - time;
2227 }
2228 }
2229
2230 mBatteryAudio.deviceOn[i] = deviceOn[i];
2231 }
2232 }
2233 return;
2234 }
2235
Marco Nelissenb7848f12014-12-04 08:57:56 -08002236 // an audio stream is started
Gloria Wang9ee159b2011-02-24 14:51:45 -08002237 if (params & kBatteryDataAudioFlingerStart) {
2238 // record the start time only if currently no other audio
2239 // is being played
2240 if (mBatteryAudio.refCount == 0) {
2241 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2242 if (mBatteryAudio.deviceOn[i]) {
2243 mBatteryAudio.lastTime[i] -= time;
2244 }
2245 }
2246 }
2247
2248 mBatteryAudio.refCount ++;
2249 return;
2250
2251 } else if (params & kBatteryDataAudioFlingerStop) {
2252 if (mBatteryAudio.refCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002253 ALOGW("Battery track warning: refCount is <= 0");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002254 return;
2255 }
2256
2257 // record the stop time only if currently this is the only
2258 // audio being played
2259 if (mBatteryAudio.refCount == 1) {
2260 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2261 if (mBatteryAudio.deviceOn[i]) {
2262 mBatteryAudio.lastTime[i] += time;
2263 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2264 mBatteryAudio.lastTime[i] = 0;
2265 }
2266 }
2267 }
2268
2269 mBatteryAudio.refCount --;
2270 return;
2271 }
2272
Gloria Wang7cf180c2011-02-19 18:37:57 -08002273 int uid = IPCThreadState::self()->getCallingUid();
2274 if (uid == AID_MEDIA) {
2275 return;
2276 }
2277 int index = mBatteryData.indexOfKey(uid);
Gloria Wang7cf180c2011-02-19 18:37:57 -08002278
2279 if (index < 0) { // create a new entry for this UID
2280 BatteryUsageInfo info;
2281 info.audioTotalTime = 0;
2282 info.videoTotalTime = 0;
2283 info.audioLastTime = 0;
2284 info.videoLastTime = 0;
2285 info.refCount = 0;
2286
Gloria Wang9ee159b2011-02-24 14:51:45 -08002287 if (mBatteryData.add(uid, info) == NO_MEMORY) {
Steve Block29357bc2012-01-06 19:20:56 +00002288 ALOGE("Battery track error: no memory for new app");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002289 return;
2290 }
Gloria Wang7cf180c2011-02-19 18:37:57 -08002291 }
2292
2293 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
2294
2295 if (params & kBatteryDataCodecStarted) {
2296 if (params & kBatteryDataTrackAudio) {
2297 info.audioLastTime -= time;
2298 info.refCount ++;
2299 }
2300 if (params & kBatteryDataTrackVideo) {
2301 info.videoLastTime -= time;
2302 info.refCount ++;
2303 }
2304 } else {
2305 if (info.refCount == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002306 ALOGW("Battery track warning: refCount is already 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002307 return;
2308 } else if (info.refCount < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00002309 ALOGE("Battery track error: refCount < 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002310 mBatteryData.removeItem(uid);
2311 return;
2312 }
2313
2314 if (params & kBatteryDataTrackAudio) {
2315 info.audioLastTime += time;
2316 info.refCount --;
2317 }
2318 if (params & kBatteryDataTrackVideo) {
2319 info.videoLastTime += time;
2320 info.refCount --;
2321 }
2322
2323 // no stream is being played by this UID
2324 if (info.refCount == 0) {
2325 info.audioTotalTime += info.audioLastTime;
2326 info.audioLastTime = 0;
2327 info.videoTotalTime += info.videoLastTime;
2328 info.videoLastTime = 0;
2329 }
2330 }
2331}
2332
2333status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
2334 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002335
2336 // audio output devices usage
2337 int32_t time = systemTime() / 1000000L; //in ms
2338 int32_t totalTime;
2339
2340 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2341 totalTime = mBatteryAudio.totalTime[i];
2342
2343 if (mBatteryAudio.deviceOn[i]
2344 && (mBatteryAudio.lastTime[i] != 0)) {
2345 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
2346 totalTime += tmpTime;
2347 }
2348
2349 reply->writeInt32(totalTime);
2350 // reset the total time
2351 mBatteryAudio.totalTime[i] = 0;
2352 }
2353
2354 // codec usage
Gloria Wang7cf180c2011-02-19 18:37:57 -08002355 BatteryUsageInfo info;
2356 int size = mBatteryData.size();
2357
2358 reply->writeInt32(size);
2359 int i = 0;
2360
2361 while (i < size) {
2362 info = mBatteryData.valueAt(i);
2363
2364 reply->writeInt32(mBatteryData.keyAt(i)); //UID
2365 reply->writeInt32(info.audioTotalTime);
2366 reply->writeInt32(info.videoTotalTime);
2367
2368 info.audioTotalTime = 0;
2369 info.videoTotalTime = 0;
2370
2371 // remove the UID entry where no stream is being played
2372 if (info.refCount <= 0) {
2373 mBatteryData.removeItemsAt(i);
2374 size --;
2375 i --;
2376 }
2377 i++;
2378 }
2379 return NO_ERROR;
2380}
nikoa64c8c72009-07-20 15:07:26 -07002381} // namespace android