blob: 8db07ca04153bd0c3b9d5f6c0b960ca1d7bbb8e1 [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>
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +010060#include <media/stagefright/AudioPlayer.h>
61#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 Huber20111aa2009-07-14 16:56:47 -070076#include "StagefrightPlayer.h"
Andreas Huberf9334412010-12-15 15:17:42 -080077#include "nuplayer/NuPlayerDriver.h"
Andreas Huber20111aa2009-07-14 16:56:47 -070078
Andreas Huber20111aa2009-07-14 16:56:47 -070079#include <OMX.h>
Nicolas Catania14d27472009-07-13 14:37:49 -070080
Andreas Hubered3e3e02012-03-26 11:13:27 -070081#include "Crypto.h"
Jeff Tinkercc82dc62013-02-08 10:18:35 -080082#include "Drm.h"
Andreas Huber59451f82012-09-18 10:36:32 -070083#include "HDCP.h"
Andreas Huberb7319a72013-05-29 14:20:52 -070084#include "HTTPBase.h"
Andreas Huber35213f12012-08-29 11:41:50 -070085#include "RemoteDisplay.h"
Andreas Hubered3e3e02012-03-26 11:13:27 -070086
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070087namespace {
nikoa64c8c72009-07-20 15:07:26 -070088using android::media::Metadata;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070089using android::status_t;
90using android::OK;
91using android::BAD_VALUE;
92using android::NOT_ENOUGH_DATA;
93using android::Parcel;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070094
95// Max number of entries in the filter.
96const int kMaxFilterSize = 64; // I pulled that out of thin air.
97
nikoa64c8c72009-07-20 15:07:26 -070098// FIXME: Move all the metadata related function in the Metadata.cpp
nikod608a812009-07-16 16:39:53 -070099
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700100
101// Unmarshall a filter from a Parcel.
102// Filter format in a parcel:
103//
104// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
105// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
106// | number of entries (n) |
107// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
108// | metadata type 1 |
109// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
110// | metadata type 2 |
111// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
112// ....
113// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
114// | metadata type n |
115// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
116//
117// @param p Parcel that should start with a filter.
118// @param[out] filter On exit contains the list of metadata type to be
119// filtered.
120// @param[out] status On exit contains the status code to be returned.
121// @return true if the parcel starts with a valid filter.
122bool unmarshallFilter(const Parcel& p,
nikoa64c8c72009-07-20 15:07:26 -0700123 Metadata::Filter *filter,
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700124 status_t *status)
125{
Nicolas Catania48290382009-07-10 13:53:06 -0700126 int32_t val;
127 if (p.readInt32(&val) != OK)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700128 {
Steve Block29357bc2012-01-06 19:20:56 +0000129 ALOGE("Failed to read filter's length");
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700130 *status = NOT_ENOUGH_DATA;
131 return false;
132 }
133
Nicolas Catania48290382009-07-10 13:53:06 -0700134 if( val > kMaxFilterSize || val < 0)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700135 {
Steve Block29357bc2012-01-06 19:20:56 +0000136 ALOGE("Invalid filter len %d", val);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700137 *status = BAD_VALUE;
138 return false;
139 }
140
Nicolas Catania48290382009-07-10 13:53:06 -0700141 const size_t num = val;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700142
143 filter->clear();
Nicolas Catania48290382009-07-10 13:53:06 -0700144 filter->setCapacity(num);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700145
nikoa64c8c72009-07-20 15:07:26 -0700146 size_t size = num * sizeof(Metadata::Type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700147
Nicolas Catania48290382009-07-10 13:53:06 -0700148
149 if (p.dataAvail() < size)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700150 {
Steve Block29357bc2012-01-06 19:20:56 +0000151 ALOGE("Filter too short expected %d but got %d", size, p.dataAvail());
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700152 *status = NOT_ENOUGH_DATA;
153 return false;
154 }
155
nikoa64c8c72009-07-20 15:07:26 -0700156 const Metadata::Type *data =
157 static_cast<const Metadata::Type*>(p.readInplace(size));
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700158
Nicolas Catania48290382009-07-10 13:53:06 -0700159 if (NULL == data)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700160 {
Steve Block29357bc2012-01-06 19:20:56 +0000161 ALOGE("Filter had no data");
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700162 *status = BAD_VALUE;
163 return false;
164 }
165
166 // TODO: The stl impl of vector would be more efficient here
167 // because it degenerates into a memcpy on pod types. Try to
168 // replace later or use stl::set.
Nicolas Catania48290382009-07-10 13:53:06 -0700169 for (size_t i = 0; i < num; ++i)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700170 {
Nicolas Catania48290382009-07-10 13:53:06 -0700171 filter->add(*data);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700172 ++data;
173 }
174 *status = OK;
175 return true;
176}
177
Nicolas Catania48290382009-07-10 13:53:06 -0700178// @param filter Of metadata type.
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700179// @param val To be searched.
180// @return true if a match was found.
nikoa64c8c72009-07-20 15:07:26 -0700181bool findMetadata(const Metadata::Filter& filter, const int32_t val)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700182{
183 // Deal with empty and ANY right away
184 if (filter.isEmpty()) return false;
nikoa64c8c72009-07-20 15:07:26 -0700185 if (filter[0] == Metadata::kAny) return true;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700186
Nicolas Catania48290382009-07-10 13:53:06 -0700187 return filter.indexOf(val) >= 0;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700188}
189
190} // anonymous namespace
191
192
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700193namespace {
194using android::Parcel;
195using android::String16;
196
197// marshalling tag indicating flattened utf16 tags
198// keep in sync with frameworks/base/media/java/android/media/AudioAttributes.java
199const int32_t kAudioAttributesMarshallTagFlattenTags = 1;
200
201// Audio attributes format in a parcel:
202//
203// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
204// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
205// | usage |
206// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
207// | content_type |
208// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Hyejin Kim4f418f92014-09-05 15:50:03 +0900209// | source |
210// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700211// | flags |
212// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
213// | kAudioAttributesMarshallTagFlattenTags | // ignore tags if not found
214// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
215// | flattened tags in UTF16 |
216// | ... |
217// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
218//
219// @param p Parcel that contains audio attributes.
220// @param[out] attributes On exit points to an initialized audio_attributes_t structure
221// @param[out] status On exit contains the status code to be returned.
222void unmarshallAudioAttributes(const Parcel& parcel, audio_attributes_t *attributes)
223{
224 attributes->usage = (audio_usage_t) parcel.readInt32();
225 attributes->content_type = (audio_content_type_t) parcel.readInt32();
Hyejin Kim4f418f92014-09-05 15:50:03 +0900226 attributes->source = (audio_source_t) parcel.readInt32();
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700227 attributes->flags = (audio_flags_mask_t) parcel.readInt32();
228 const bool hasFlattenedTag = (parcel.readInt32() == kAudioAttributesMarshallTagFlattenTags);
229 if (hasFlattenedTag) {
230 // the tags are UTF16, convert to UTF8
231 String16 tags = parcel.readString16();
232 ssize_t realTagSize = utf16_to_utf8_length(tags.string(), tags.size());
233 if (realTagSize <= 0) {
234 strcpy(attributes->tags, "");
235 } else {
236 // copy the flattened string into the attributes as the destination for the conversion:
237 // copying array size -1, array for tags was calloc'd, no need to NULL-terminate it
238 size_t tagSize = realTagSize > AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 ?
239 AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 : realTagSize;
240 utf16_to_utf8(tags.string(), tagSize, attributes->tags);
241 }
242 } else {
243 ALOGE("unmarshallAudioAttributes() received unflattened tags, ignoring tag values");
244 strcpy(attributes->tags, "");
245 }
246}
247} // anonymous namespace
248
249
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800250namespace android {
251
Marco Nelissenf09611f2015-02-13 14:12:42 -0800252extern ALooperRoster gLooperRoster;
253
254
Dave Burked681bbb2011-08-30 14:39:17 +0100255static bool checkPermission(const char* permissionString) {
Dave Burked681bbb2011-08-30 14:39:17 +0100256 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
257 bool ok = checkCallingPermission(String16(permissionString));
Steve Block29357bc2012-01-06 19:20:56 +0000258 if (!ok) ALOGE("Request requires %s", permissionString);
Dave Burked681bbb2011-08-30 14:39:17 +0100259 return ok;
260}
261
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800262// 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 -0800263/* static */ int MediaPlayerService::AudioOutput::mMinBufferCount = 4;
264/* static */ bool MediaPlayerService::AudioOutput::mIsOnEmulator = false;
265
266void MediaPlayerService::instantiate() {
267 defaultServiceManager()->addService(
268 String16("media.player"), new MediaPlayerService());
269}
270
271MediaPlayerService::MediaPlayerService()
272{
Steve Block3856b092011-10-20 11:56:00 +0100273 ALOGV("MediaPlayerService created");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800274 mNextConnId = 1;
Gloria Wang9ee159b2011-02-24 14:51:45 -0800275
276 mBatteryAudio.refCount = 0;
277 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
278 mBatteryAudio.deviceOn[i] = 0;
279 mBatteryAudio.lastTime[i] = 0;
280 mBatteryAudio.totalTime[i] = 0;
281 }
282 // speaker is on by default
283 mBatteryAudio.deviceOn[SPEAKER] = 1;
John Grossman44a7e422012-06-21 17:29:24 -0700284
Chong Zhang0b30fd42014-07-23 14:46:05 -0700285 // reset battery stats
286 // if the mediaserver has crashed, battery stats could be left
287 // in bad state, reset the state upon service start.
Ruben Brunk99e69712015-05-26 17:25:07 -0700288 BatteryNotifier& notifier(BatteryNotifier::getInstance());
289 notifier.noteResetVideo();
290 notifier.noteResetAudio();
Chong Zhang0b30fd42014-07-23 14:46:05 -0700291
John Grossman44a7e422012-06-21 17:29:24 -0700292 MediaPlayerFactory::registerBuiltinFactories();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800293}
294
295MediaPlayerService::~MediaPlayerService()
296{
Steve Block3856b092011-10-20 11:56:00 +0100297 ALOGV("MediaPlayerService destroyed");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800298}
299
Svet Ganovbe71aa22015-04-28 12:06:02 -0700300sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(const String16 &opPackageName)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800301{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800302 pid_t pid = IPCThreadState::self()->getCallingPid();
Svet Ganovbe71aa22015-04-28 12:06:02 -0700303 sp<MediaRecorderClient> recorder = new MediaRecorderClient(this, pid, opPackageName);
Gloria Wangdac6a312009-10-29 15:46:37 -0700304 wp<MediaRecorderClient> w = recorder;
305 Mutex::Autolock lock(mLock);
306 mMediaRecorderClients.add(w);
Steve Block3856b092011-10-20 11:56:00 +0100307 ALOGV("Create new media recorder client from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800308 return recorder;
309}
310
Gloria Wangdac6a312009-10-29 15:46:37 -0700311void MediaPlayerService::removeMediaRecorderClient(wp<MediaRecorderClient> client)
312{
313 Mutex::Autolock lock(mLock);
314 mMediaRecorderClients.remove(client);
Steve Block3856b092011-10-20 11:56:00 +0100315 ALOGV("Delete media recorder client");
Gloria Wangdac6a312009-10-29 15:46:37 -0700316}
317
Glenn Kastenf37971f2012-02-03 11:06:53 -0800318sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800319{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800320 pid_t pid = IPCThreadState::self()->getCallingPid();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800321 sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
Steve Block3856b092011-10-20 11:56:00 +0100322 ALOGV("Create new media retriever from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800323 return retriever;
324}
325
Glenn Kastenf37971f2012-02-03 11:06:53 -0800326sp<IMediaPlayer> MediaPlayerService::create(const sp<IMediaPlayerClient>& client,
Dave Burked681bbb2011-08-30 14:39:17 +0100327 int audioSessionId)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800328{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800329 pid_t pid = IPCThreadState::self()->getCallingPid();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800330 int32_t connId = android_atomic_inc(&mNextConnId);
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700331
332 sp<Client> c = new Client(
333 this, pid, connId, client, audioSessionId,
334 IPCThreadState::self()->getCallingUid());
335
Steve Block3856b092011-10-20 11:56:00 +0100336 ALOGV("Create new client(%d) from pid %d, uid %d, ", connId, pid,
Dave Burked681bbb2011-08-30 14:39:17 +0100337 IPCThreadState::self()->getCallingUid());
338
339 wp<Client> w = c;
340 {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800341 Mutex::Autolock lock(mLock);
342 mClients.add(w);
343 }
Andreas Hubere2b10282010-11-23 11:41:34 -0800344 return c;
345}
346
Lajos Molnar1381d4b2014-08-07 15:18:35 -0700347sp<IMediaCodecList> MediaPlayerService::getCodecList() const {
348 return MediaCodecList::getLocalInstance();
349}
350
Andreas Huber318ad9c2009-10-15 13:46:54 -0700351sp<IOMX> MediaPlayerService::getOMX() {
352 Mutex::Autolock autoLock(mLock);
353
354 if (mOMX.get() == NULL) {
355 mOMX = new OMX;
356 }
357
358 return mOMX;
Andreas Huber20111aa2009-07-14 16:56:47 -0700359}
360
Andreas Hubered3e3e02012-03-26 11:13:27 -0700361sp<ICrypto> MediaPlayerService::makeCrypto() {
Andreas Huber1bd139a2012-04-03 14:19:20 -0700362 return new Crypto;
Andreas Hubered3e3e02012-03-26 11:13:27 -0700363}
364
Jeff Tinkercc82dc62013-02-08 10:18:35 -0800365sp<IDrm> MediaPlayerService::makeDrm() {
366 return new Drm;
367}
368
Andreas Huber279dcd82013-01-30 10:41:25 -0800369sp<IHDCP> MediaPlayerService::makeHDCP(bool createEncryptionModule) {
370 return new HDCP(createEncryptionModule);
Andreas Huber59451f82012-09-18 10:36:32 -0700371}
372
Jeff Brown2013a542012-09-04 21:38:42 -0700373sp<IRemoteDisplay> MediaPlayerService::listenForRemoteDisplay(
Svet Ganovbe71aa22015-04-28 12:06:02 -0700374 const String16 &opPackageName,
Jeff Brown2013a542012-09-04 21:38:42 -0700375 const sp<IRemoteDisplayClient>& client, const String8& iface) {
Jeff Brownaba33d52012-09-07 17:38:58 -0700376 if (!checkPermission("android.permission.CONTROL_WIFI_DISPLAY")) {
377 return NULL;
378 }
379
Svet Ganovbe71aa22015-04-28 12:06:02 -0700380 return new RemoteDisplay(opPackageName, client, iface.string());
Jeff Brown2013a542012-09-04 21:38:42 -0700381}
382
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800383status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
384{
385 const size_t SIZE = 256;
386 char buffer[SIZE];
387 String8 result;
388
389 result.append(" AudioOutput\n");
390 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n",
391 mStreamType, mLeftVolume, mRightVolume);
392 result.append(buffer);
393 snprintf(buffer, 255, " msec per frame(%f), latency (%d)\n",
Eric Laurentdb354e52012-03-05 17:27:11 -0800394 mMsecsPerFrame, (mTrack != 0) ? mTrack->latency() : -1);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800395 result.append(buffer);
Eric Laurent2beeb502010-07-16 07:43:46 -0700396 snprintf(buffer, 255, " aux effect id(%d), send level (%f)\n",
397 mAuxEffectId, mSendLevel);
398 result.append(buffer);
399
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800400 ::write(fd, result.string(), result.size());
401 if (mTrack != 0) {
402 mTrack->dump(fd, args);
403 }
404 return NO_ERROR;
405}
406
Lajos Molnar6d339f12015-04-17 16:15:53 -0700407status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800408{
409 const size_t SIZE = 256;
410 char buffer[SIZE];
411 String8 result;
412 result.append(" Client\n");
413 snprintf(buffer, 255, " pid(%d), connId(%d), status(%d), looping(%s)\n",
414 mPid, mConnId, mStatus, mLoop?"true": "false");
415 result.append(buffer);
416 write(fd, result.string(), result.size());
Andreas Hubera0b1d4b2011-06-07 15:52:25 -0700417 if (mPlayer != NULL) {
418 mPlayer->dump(fd, args);
419 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800420 if (mAudioOutput != 0) {
421 mAudioOutput->dump(fd, args);
422 }
423 write(fd, "\n", 1);
424 return NO_ERROR;
425}
426
Marco Nelissenf09611f2015-02-13 14:12:42 -0800427/**
428 * The only arguments this understands right now are -c, -von and -voff,
429 * which are parsed by ALooperRoster::dump()
430 */
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800431status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
432{
433 const size_t SIZE = 256;
434 char buffer[SIZE];
435 String8 result;
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530436 SortedVector< sp<Client> > clients; //to serialise the mutex unlock & client destruction.
437 SortedVector< sp<MediaRecorderClient> > mediaRecorderClients;
438
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800439 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
440 snprintf(buffer, SIZE, "Permission Denial: "
441 "can't dump MediaPlayerService from pid=%d, uid=%d\n",
442 IPCThreadState::self()->getCallingPid(),
443 IPCThreadState::self()->getCallingUid());
444 result.append(buffer);
445 } else {
446 Mutex::Autolock lock(mLock);
447 for (int i = 0, n = mClients.size(); i < n; ++i) {
448 sp<Client> c = mClients[i].promote();
449 if (c != 0) c->dump(fd, args);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530450 clients.add(c);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800451 }
James Dongb9141222010-07-08 11:16:11 -0700452 if (mMediaRecorderClients.size() == 0) {
453 result.append(" No media recorder client\n\n");
454 } else {
455 for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
456 sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
James Donge579e282011-10-18 22:29:20 -0700457 if (c != 0) {
458 snprintf(buffer, 255, " MediaRecorderClient pid(%d)\n", c->mPid);
459 result.append(buffer);
460 write(fd, result.string(), result.size());
461 result = "\n";
462 c->dump(fd, args);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530463 mediaRecorderClients.add(c);
James Donge579e282011-10-18 22:29:20 -0700464 }
James Dongb9141222010-07-08 11:16:11 -0700465 }
Gloria Wangdac6a312009-10-29 15:46:37 -0700466 }
467
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800468 result.append(" Files opened and/or mapped:\n");
Marco Nelissenf09611f2015-02-13 14:12:42 -0800469 snprintf(buffer, SIZE, "/proc/%d/maps", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800470 FILE *f = fopen(buffer, "r");
471 if (f) {
472 while (!feof(f)) {
473 fgets(buffer, SIZE, f);
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700474 if (strstr(buffer, " /storage/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800475 strstr(buffer, " /system/sounds/") ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700476 strstr(buffer, " /data/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800477 strstr(buffer, " /system/media/")) {
478 result.append(" ");
479 result.append(buffer);
480 }
481 }
482 fclose(f);
483 } else {
484 result.append("couldn't open ");
485 result.append(buffer);
486 result.append("\n");
487 }
488
Marco Nelissenf09611f2015-02-13 14:12:42 -0800489 snprintf(buffer, SIZE, "/proc/%d/fd", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800490 DIR *d = opendir(buffer);
491 if (d) {
492 struct dirent *ent;
493 while((ent = readdir(d)) != NULL) {
494 if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
Marco Nelissenf09611f2015-02-13 14:12:42 -0800495 snprintf(buffer, SIZE, "/proc/%d/fd/%s", getpid(), ent->d_name);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800496 struct stat s;
497 if (lstat(buffer, &s) == 0) {
498 if ((s.st_mode & S_IFMT) == S_IFLNK) {
499 char linkto[256];
500 int len = readlink(buffer, linkto, sizeof(linkto));
501 if(len > 0) {
502 if(len > 255) {
503 linkto[252] = '.';
504 linkto[253] = '.';
505 linkto[254] = '.';
506 linkto[255] = 0;
507 } else {
508 linkto[len] = 0;
509 }
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700510 if (strstr(linkto, "/storage/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800511 strstr(linkto, "/system/sounds/") == linkto ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700512 strstr(linkto, "/data/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800513 strstr(linkto, "/system/media/") == linkto) {
514 result.append(" ");
515 result.append(buffer);
516 result.append(" -> ");
517 result.append(linkto);
518 result.append("\n");
519 }
520 }
521 } else {
522 result.append(" unexpected type for ");
523 result.append(buffer);
524 result.append("\n");
525 }
526 }
527 }
528 }
529 closedir(d);
530 } else {
531 result.append("couldn't open ");
532 result.append(buffer);
533 result.append("\n");
534 }
535
Marco Nelissenf09611f2015-02-13 14:12:42 -0800536 gLooperRoster.dump(fd, args);
537
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800538 bool dumpMem = false;
539 for (size_t i = 0; i < args.size(); i++) {
540 if (args[i] == String16("-m")) {
541 dumpMem = true;
542 }
543 }
544 if (dumpMem) {
James Dong8635b7b2011-03-14 17:01:38 -0700545 dumpMemoryAddresses(fd);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800546 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800547 }
548 write(fd, result.string(), result.size());
549 return NO_ERROR;
550}
551
552void MediaPlayerService::removeClient(wp<Client> client)
553{
554 Mutex::Autolock lock(mLock);
555 mClients.remove(client);
556}
557
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700558MediaPlayerService::Client::Client(
559 const sp<MediaPlayerService>& service, pid_t pid,
560 int32_t connId, const sp<IMediaPlayerClient>& client,
561 int audioSessionId, uid_t uid)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800562{
Steve Block3856b092011-10-20 11:56:00 +0100563 ALOGV("Client(%d) constructor", connId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800564 mPid = pid;
565 mConnId = connId;
566 mService = service;
567 mClient = client;
568 mLoop = false;
569 mStatus = NO_INIT;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700570 mAudioSessionId = audioSessionId;
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700571 mUID = uid;
John Grossmanc795b642012-02-22 15:38:35 -0800572 mRetransmitEndpointValid = false;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700573 mAudioAttributes = NULL;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700574
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800575#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000576 ALOGD("create Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800577 mAntagonizer = new Antagonizer(notify, this);
578#endif
579}
580
581MediaPlayerService::Client::~Client()
582{
Steve Block3856b092011-10-20 11:56:00 +0100583 ALOGV("Client(%d) destructor pid = %d", mConnId, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800584 mAudioOutput.clear();
585 wp<Client> client(this);
586 disconnect();
587 mService->removeClient(client);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700588 if (mAudioAttributes != NULL) {
589 free(mAudioAttributes);
590 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800591}
592
593void MediaPlayerService::Client::disconnect()
594{
Steve Block3856b092011-10-20 11:56:00 +0100595 ALOGV("disconnect(%d) from pid %d", mConnId, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800596 // grab local reference and clear main reference to prevent future
597 // access to object
598 sp<MediaPlayerBase> p;
599 {
600 Mutex::Autolock l(mLock);
601 p = mPlayer;
beanzdcfefde2012-11-05 09:51:43 +0800602 mClient.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800603 }
Andreas Huber20111aa2009-07-14 16:56:47 -0700604
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800605 mPlayer.clear();
606
607 // clear the notification to prevent callbacks to dead client
608 // and reset the player. We assume the player will serialize
609 // access to itself if necessary.
610 if (p != 0) {
611 p->setNotifyCallback(0, 0);
612#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000613 ALOGD("kill Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800614 mAntagonizer->kill();
615#endif
616 p->reset();
617 }
618
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700619 disconnectNativeWindow();
620
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800621 IPCThreadState::self()->flushCommands();
622}
623
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800624sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
625{
626 // determine if we have the right player type
627 sp<MediaPlayerBase> p = mPlayer;
628 if ((p != NULL) && (p->playerType() != playerType)) {
Steve Block3856b092011-10-20 11:56:00 +0100629 ALOGV("delete player");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800630 p.clear();
631 }
632 if (p == NULL) {
Ronghua Wu68845c12015-07-21 09:50:48 -0700633 p = MediaPlayerFactory::createPlayer(playerType, this, notify, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800634 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700635
Jason Simmonsdb29e522011-08-12 13:46:55 -0700636 if (p != NULL) {
637 p->setUID(mUID);
638 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700639
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800640 return p;
641}
642
John Grossmanc795b642012-02-22 15:38:35 -0800643sp<MediaPlayerBase> MediaPlayerService::Client::setDataSource_pre(
644 player_type playerType)
645{
646 ALOGV("player type = %d", playerType);
647
648 // create the right type of player
649 sp<MediaPlayerBase> p = createPlayer(playerType);
650 if (p == NULL) {
651 return p;
652 }
653
654 if (!p->hardwareOutput()) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -0700655 Mutex::Autolock l(mLock);
Marco Nelissend457c972014-02-11 08:47:07 -0800656 mAudioOutput = new AudioOutput(mAudioSessionId, IPCThreadState::self()->getCallingUid(),
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700657 mPid, mAudioAttributes);
John Grossmanc795b642012-02-22 15:38:35 -0800658 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
659 }
660
661 return p;
662}
663
664void MediaPlayerService::Client::setDataSource_post(
665 const sp<MediaPlayerBase>& p,
666 status_t status)
667{
668 ALOGV(" setDataSource");
669 mStatus = status;
670 if (mStatus != OK) {
671 ALOGE(" error: %d", mStatus);
672 return;
673 }
674
675 // Set the re-transmission endpoint if one was chosen.
676 if (mRetransmitEndpointValid) {
677 mStatus = p->setRetransmitEndpoint(&mRetransmitEndpoint);
678 if (mStatus != NO_ERROR) {
679 ALOGE("setRetransmitEndpoint error: %d", mStatus);
680 }
681 }
682
683 if (mStatus == OK) {
684 mPlayer = p;
685 }
686}
687
Andreas Huber2db84552010-01-28 11:19:57 -0800688status_t MediaPlayerService::Client::setDataSource(
Andreas Huber1b86fe02014-01-29 11:13:26 -0800689 const sp<IMediaHTTPService> &httpService,
690 const char *url,
691 const KeyedVector<String8, String8> *headers)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800692{
Steve Block3856b092011-10-20 11:56:00 +0100693 ALOGV("setDataSource(%s)", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800694 if (url == NULL)
695 return UNKNOWN_ERROR;
696
Dave Burked681bbb2011-08-30 14:39:17 +0100697 if ((strncmp(url, "http://", 7) == 0) ||
698 (strncmp(url, "https://", 8) == 0) ||
699 (strncmp(url, "rtsp://", 7) == 0)) {
700 if (!checkPermission("android.permission.INTERNET")) {
701 return PERMISSION_DENIED;
702 }
703 }
704
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800705 if (strncmp(url, "content://", 10) == 0) {
706 // get a filedescriptor for the content Uri and
707 // pass it to the setDataSource(fd) method
708
709 String16 url16(url);
710 int fd = android::openContentProviderFile(url16);
711 if (fd < 0)
712 {
Steve Block29357bc2012-01-06 19:20:56 +0000713 ALOGE("Couldn't open fd for %s", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800714 return UNKNOWN_ERROR;
715 }
716 setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
717 close(fd);
718 return mStatus;
719 } else {
John Grossman44a7e422012-06-21 17:29:24 -0700720 player_type playerType = MediaPlayerFactory::getPlayerType(this, url);
John Grossmanc795b642012-02-22 15:38:35 -0800721 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
722 if (p == NULL) {
723 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800724 }
725
Andreas Huber1b86fe02014-01-29 11:13:26 -0800726 setDataSource_post(p, p->setDataSource(httpService, url, headers));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800727 return mStatus;
728 }
729}
730
731status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
732{
Steve Block3856b092011-10-20 11:56:00 +0100733 ALOGV("setDataSource fd=%d, offset=%lld, length=%lld", fd, offset, length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800734 struct stat sb;
735 int ret = fstat(fd, &sb);
736 if (ret != 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000737 ALOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800738 return UNKNOWN_ERROR;
739 }
740
Ying Wang5fde15d2015-04-20 22:13:22 -0700741 ALOGV("st_dev = %llu", static_cast<uint64_t>(sb.st_dev));
Steve Block3856b092011-10-20 11:56:00 +0100742 ALOGV("st_mode = %u", sb.st_mode);
Mark Salyzyn77342f72014-06-18 16:31:32 -0700743 ALOGV("st_uid = %lu", static_cast<unsigned long>(sb.st_uid));
744 ALOGV("st_gid = %lu", static_cast<unsigned long>(sb.st_gid));
Steve Block3856b092011-10-20 11:56:00 +0100745 ALOGV("st_size = %llu", sb.st_size);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800746
747 if (offset >= sb.st_size) {
Steve Block29357bc2012-01-06 19:20:56 +0000748 ALOGE("offset error");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800749 return UNKNOWN_ERROR;
750 }
751 if (offset + length > sb.st_size) {
752 length = sb.st_size - offset;
Steve Block3856b092011-10-20 11:56:00 +0100753 ALOGV("calculated length = %lld", length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800754 }
755
John Grossman44a7e422012-06-21 17:29:24 -0700756 player_type playerType = MediaPlayerFactory::getPlayerType(this,
757 fd,
758 offset,
759 length);
John Grossmanc795b642012-02-22 15:38:35 -0800760 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
761 if (p == NULL) {
762 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800763 }
764
765 // now set data source
John Grossmanc795b642012-02-22 15:38:35 -0800766 setDataSource_post(p, p->setDataSource(fd, offset, length));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800767 return mStatus;
768}
769
Andreas Hubere2b10282010-11-23 11:41:34 -0800770status_t MediaPlayerService::Client::setDataSource(
771 const sp<IStreamSource> &source) {
772 // create the right type of player
John Grossman44a7e422012-06-21 17:29:24 -0700773 player_type playerType = MediaPlayerFactory::getPlayerType(this, source);
John Grossmanc795b642012-02-22 15:38:35 -0800774 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
Andreas Hubere2b10282010-11-23 11:41:34 -0800775 if (p == NULL) {
776 return NO_INIT;
777 }
778
Andreas Hubere2b10282010-11-23 11:41:34 -0800779 // now set data source
John Grossmanc795b642012-02-22 15:38:35 -0800780 setDataSource_post(p, p->setDataSource(source));
Andreas Hubere2b10282010-11-23 11:41:34 -0800781 return mStatus;
782}
783
Chris Watkins99f31602015-03-20 13:06:33 -0700784status_t MediaPlayerService::Client::setDataSource(
785 const sp<IDataSource> &source) {
786 sp<DataSource> dataSource = DataSource::CreateFromIDataSource(source);
787 player_type playerType = MediaPlayerFactory::getPlayerType(this, dataSource);
788 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
789 if (p == NULL) {
790 return NO_INIT;
791 }
792 // now set data source
793 setDataSource_post(p, p->setDataSource(dataSource));
794 return mStatus;
795}
796
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700797void MediaPlayerService::Client::disconnectNativeWindow() {
798 if (mConnectedWindow != NULL) {
799 status_t err = native_window_api_disconnect(mConnectedWindow.get(),
800 NATIVE_WINDOW_API_MEDIA);
801
802 if (err != OK) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000803 ALOGW("native_window_api_disconnect returned an error: %s (%d)",
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700804 strerror(-err), err);
805 }
806 }
807 mConnectedWindow.clear();
808}
809
Glenn Kasten11731182011-02-08 17:26:17 -0800810status_t MediaPlayerService::Client::setVideoSurfaceTexture(
Andy McFadden484566c2012-12-18 09:46:54 -0800811 const sp<IGraphicBufferProducer>& bufferProducer)
Glenn Kasten11731182011-02-08 17:26:17 -0800812{
Andy McFadden484566c2012-12-18 09:46:54 -0800813 ALOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, bufferProducer.get());
Glenn Kasten11731182011-02-08 17:26:17 -0800814 sp<MediaPlayerBase> p = getPlayer();
815 if (p == 0) return UNKNOWN_ERROR;
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700816
Marco Nelissenf8880202014-11-14 07:58:25 -0800817 sp<IBinder> binder(IInterface::asBinder(bufferProducer));
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700818 if (mConnectedWindowBinder == binder) {
819 return OK;
820 }
821
822 sp<ANativeWindow> anw;
Andy McFadden484566c2012-12-18 09:46:54 -0800823 if (bufferProducer != NULL) {
Marco Nelissenee08f7e2013-09-16 13:30:01 -0700824 anw = new Surface(bufferProducer, true /* controlledByApp */);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700825 status_t err = native_window_api_connect(anw.get(),
826 NATIVE_WINDOW_API_MEDIA);
827
828 if (err != OK) {
Steve Block29357bc2012-01-06 19:20:56 +0000829 ALOGE("setVideoSurfaceTexture failed: %d", err);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700830 // Note that we must do the reset before disconnecting from the ANW.
831 // Otherwise queue/dequeue calls could be made on the disconnected
832 // ANW, which may result in errors.
833 reset();
834
835 disconnectNativeWindow();
836
837 return err;
838 }
839 }
840
Andy McFadden484566c2012-12-18 09:46:54 -0800841 // Note that we must set the player's new GraphicBufferProducer before
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700842 // disconnecting the old one. Otherwise queue/dequeue calls could be made
843 // on the disconnected ANW, which may result in errors.
Andy McFadden484566c2012-12-18 09:46:54 -0800844 status_t err = p->setVideoSurfaceTexture(bufferProducer);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700845
846 disconnectNativeWindow();
847
848 mConnectedWindow = anw;
849
850 if (err == OK) {
851 mConnectedWindowBinder = binder;
852 } else {
853 disconnectNativeWindow();
854 }
855
856 return err;
Glenn Kasten11731182011-02-08 17:26:17 -0800857}
858
Nicolas Catania1d187f12009-05-12 23:25:55 -0700859status_t MediaPlayerService::Client::invoke(const Parcel& request,
860 Parcel *reply)
861{
862 sp<MediaPlayerBase> p = getPlayer();
863 if (p == NULL) return UNKNOWN_ERROR;
864 return p->invoke(request, reply);
865}
866
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700867// This call doesn't need to access the native player.
868status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
869{
870 status_t status;
nikoa64c8c72009-07-20 15:07:26 -0700871 media::Metadata::Filter allow, drop;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700872
Nicolas Catania48290382009-07-10 13:53:06 -0700873 if (unmarshallFilter(filter, &allow, &status) &&
874 unmarshallFilter(filter, &drop, &status)) {
875 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700876
877 mMetadataAllow = allow;
878 mMetadataDrop = drop;
879 }
880 return status;
881}
882
Nicolas Catania48290382009-07-10 13:53:06 -0700883status_t MediaPlayerService::Client::getMetadata(
Mark Salyzyn77342f72014-06-18 16:31:32 -0700884 bool update_only, bool /*apply_filter*/, Parcel *reply)
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700885{
nikoa64c8c72009-07-20 15:07:26 -0700886 sp<MediaPlayerBase> player = getPlayer();
887 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania48290382009-07-10 13:53:06 -0700888
nikod608a812009-07-16 16:39:53 -0700889 status_t status;
890 // Placeholder for the return code, updated by the caller.
891 reply->writeInt32(-1);
892
nikoa64c8c72009-07-20 15:07:26 -0700893 media::Metadata::Filter ids;
Nicolas Catania48290382009-07-10 13:53:06 -0700894
895 // We don't block notifications while we fetch the data. We clear
896 // mMetadataUpdated first so we don't lose notifications happening
897 // during the rest of this call.
898 {
899 Mutex::Autolock lock(mLock);
900 if (update_only) {
nikod608a812009-07-16 16:39:53 -0700901 ids = mMetadataUpdated;
Nicolas Catania48290382009-07-10 13:53:06 -0700902 }
903 mMetadataUpdated.clear();
904 }
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700905
nikoa64c8c72009-07-20 15:07:26 -0700906 media::Metadata metadata(reply);
Nicolas Catania48290382009-07-10 13:53:06 -0700907
nikoa64c8c72009-07-20 15:07:26 -0700908 metadata.appendHeader();
909 status = player->getMetadata(ids, reply);
nikod608a812009-07-16 16:39:53 -0700910
911 if (status != OK) {
nikoa64c8c72009-07-20 15:07:26 -0700912 metadata.resetParcel();
Steve Block29357bc2012-01-06 19:20:56 +0000913 ALOGE("getMetadata failed %d", status);
nikod608a812009-07-16 16:39:53 -0700914 return status;
915 }
916
917 // FIXME: Implement filtering on the result. Not critical since
918 // filtering takes place on the update notifications already. This
919 // would be when all the metadata are fetch and a filter is set.
920
nikod608a812009-07-16 16:39:53 -0700921 // Everything is fine, update the metadata length.
nikoa64c8c72009-07-20 15:07:26 -0700922 metadata.updateLength();
nikod608a812009-07-16 16:39:53 -0700923 return OK;
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700924}
925
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800926status_t MediaPlayerService::Client::prepareAsync()
927{
Steve Block3856b092011-10-20 11:56:00 +0100928 ALOGV("[%d] prepareAsync", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800929 sp<MediaPlayerBase> p = getPlayer();
930 if (p == 0) return UNKNOWN_ERROR;
931 status_t ret = p->prepareAsync();
932#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000933 ALOGD("start Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800934 if (ret == NO_ERROR) mAntagonizer->start();
935#endif
936 return ret;
937}
938
939status_t MediaPlayerService::Client::start()
940{
Steve Block3856b092011-10-20 11:56:00 +0100941 ALOGV("[%d] start", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800942 sp<MediaPlayerBase> p = getPlayer();
943 if (p == 0) return UNKNOWN_ERROR;
944 p->setLooping(mLoop);
945 return p->start();
946}
947
948status_t MediaPlayerService::Client::stop()
949{
Steve Block3856b092011-10-20 11:56:00 +0100950 ALOGV("[%d] stop", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800951 sp<MediaPlayerBase> p = getPlayer();
952 if (p == 0) return UNKNOWN_ERROR;
953 return p->stop();
954}
955
956status_t MediaPlayerService::Client::pause()
957{
Steve Block3856b092011-10-20 11:56:00 +0100958 ALOGV("[%d] pause", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800959 sp<MediaPlayerBase> p = getPlayer();
960 if (p == 0) return UNKNOWN_ERROR;
961 return p->pause();
962}
963
964status_t MediaPlayerService::Client::isPlaying(bool* state)
965{
966 *state = false;
967 sp<MediaPlayerBase> p = getPlayer();
968 if (p == 0) return UNKNOWN_ERROR;
969 *state = p->isPlaying();
Steve Block3856b092011-10-20 11:56:00 +0100970 ALOGV("[%d] isPlaying: %d", mConnId, *state);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800971 return NO_ERROR;
972}
973
Lajos Molnar3a474aa2015-04-24 17:10:07 -0700974status_t MediaPlayerService::Client::setPlaybackSettings(const AudioPlaybackRate& rate)
Wei Jia98160162015-02-04 17:01:11 -0800975{
Lajos Molnar3a474aa2015-04-24 17:10:07 -0700976 ALOGV("[%d] setPlaybackSettings(%f, %f, %d, %d)",
977 mConnId, rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Wei Jia98160162015-02-04 17:01:11 -0800978 sp<MediaPlayerBase> p = getPlayer();
979 if (p == 0) return UNKNOWN_ERROR;
Lajos Molnar3a474aa2015-04-24 17:10:07 -0700980 return p->setPlaybackSettings(rate);
981}
982
983status_t MediaPlayerService::Client::getPlaybackSettings(AudioPlaybackRate* rate /* nonnull */)
984{
985 sp<MediaPlayerBase> p = getPlayer();
986 if (p == 0) return UNKNOWN_ERROR;
987 status_t ret = p->getPlaybackSettings(rate);
988 if (ret == NO_ERROR) {
989 ALOGV("[%d] getPlaybackSettings(%f, %f, %d, %d)",
990 mConnId, rate->mSpeed, rate->mPitch, rate->mFallbackMode, rate->mStretchMode);
991 } else {
992 ALOGV("[%d] getPlaybackSettings returned %d", mConnId, ret);
993 }
994 return ret;
995}
996
997status_t MediaPlayerService::Client::setSyncSettings(
998 const AVSyncSettings& sync, float videoFpsHint)
999{
1000 ALOGV("[%d] setSyncSettings(%u, %u, %f, %f)",
1001 mConnId, sync.mSource, sync.mAudioAdjustMode, sync.mTolerance, videoFpsHint);
1002 sp<MediaPlayerBase> p = getPlayer();
1003 if (p == 0) return UNKNOWN_ERROR;
1004 return p->setSyncSettings(sync, videoFpsHint);
1005}
1006
1007status_t MediaPlayerService::Client::getSyncSettings(
1008 AVSyncSettings* sync /* nonnull */, float* videoFps /* nonnull */)
1009{
1010 sp<MediaPlayerBase> p = getPlayer();
1011 if (p == 0) return UNKNOWN_ERROR;
1012 status_t ret = p->getSyncSettings(sync, videoFps);
1013 if (ret == NO_ERROR) {
1014 ALOGV("[%d] getSyncSettings(%u, %u, %f, %f)",
1015 mConnId, sync->mSource, sync->mAudioAdjustMode, sync->mTolerance, *videoFps);
1016 } else {
1017 ALOGV("[%d] getSyncSettings returned %d", mConnId, ret);
1018 }
1019 return ret;
Wei Jia98160162015-02-04 17:01:11 -08001020}
1021
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001022status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
1023{
Steve Block3856b092011-10-20 11:56:00 +01001024 ALOGV("getCurrentPosition");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001025 sp<MediaPlayerBase> p = getPlayer();
1026 if (p == 0) return UNKNOWN_ERROR;
1027 status_t ret = p->getCurrentPosition(msec);
1028 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001029 ALOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001030 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001031 ALOGE("getCurrentPosition returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001032 }
1033 return ret;
1034}
1035
1036status_t MediaPlayerService::Client::getDuration(int *msec)
1037{
Steve Block3856b092011-10-20 11:56:00 +01001038 ALOGV("getDuration");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001039 sp<MediaPlayerBase> p = getPlayer();
1040 if (p == 0) return UNKNOWN_ERROR;
1041 status_t ret = p->getDuration(msec);
1042 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001043 ALOGV("[%d] getDuration = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001044 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001045 ALOGE("getDuration returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001046 }
1047 return ret;
1048}
1049
Marco Nelissen6b74d672012-02-28 16:07:44 -08001050status_t MediaPlayerService::Client::setNextPlayer(const sp<IMediaPlayer>& player) {
1051 ALOGV("setNextPlayer");
1052 Mutex::Autolock l(mLock);
1053 sp<Client> c = static_cast<Client*>(player.get());
1054 mNextClient = c;
John Grossman5f7e55e2012-08-24 14:47:25 -07001055
1056 if (c != NULL) {
1057 if (mAudioOutput != NULL) {
1058 mAudioOutput->setNextOutput(c->mAudioOutput);
1059 } else if ((mPlayer != NULL) && !mPlayer->hardwareOutput()) {
1060 ALOGE("no current audio output");
1061 }
1062
1063 if ((mPlayer != NULL) && (mNextClient->getPlayer() != NULL)) {
1064 mPlayer->setNextPlayer(mNextClient->getPlayer());
1065 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001066 }
John Grossman5f7e55e2012-08-24 14:47:25 -07001067
Marco Nelissen6b74d672012-02-28 16:07:44 -08001068 return OK;
1069}
1070
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001071status_t MediaPlayerService::Client::seekTo(int msec)
1072{
Steve Block3856b092011-10-20 11:56:00 +01001073 ALOGV("[%d] seekTo(%d)", mConnId, msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001074 sp<MediaPlayerBase> p = getPlayer();
1075 if (p == 0) return UNKNOWN_ERROR;
1076 return p->seekTo(msec);
1077}
1078
1079status_t MediaPlayerService::Client::reset()
1080{
Steve Block3856b092011-10-20 11:56:00 +01001081 ALOGV("[%d] reset", mConnId);
John Grossmanc795b642012-02-22 15:38:35 -08001082 mRetransmitEndpointValid = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001083 sp<MediaPlayerBase> p = getPlayer();
1084 if (p == 0) return UNKNOWN_ERROR;
1085 return p->reset();
1086}
1087
Glenn Kastenfff6d712012-01-12 16:38:12 -08001088status_t MediaPlayerService::Client::setAudioStreamType(audio_stream_type_t type)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001089{
Steve Block3856b092011-10-20 11:56:00 +01001090 ALOGV("[%d] setAudioStreamType(%d)", mConnId, type);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001091 // TODO: for hardware output, call player instead
1092 Mutex::Autolock l(mLock);
1093 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1094 return NO_ERROR;
1095}
1096
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001097status_t MediaPlayerService::Client::setAudioAttributes_l(const Parcel &parcel)
1098{
1099 if (mAudioAttributes != NULL) { free(mAudioAttributes); }
1100 mAudioAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001101 if (mAudioAttributes == NULL) {
1102 return NO_MEMORY;
1103 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001104 unmarshallAudioAttributes(parcel, mAudioAttributes);
1105
1106 ALOGV("setAudioAttributes_l() usage=%d content=%d flags=0x%x tags=%s",
1107 mAudioAttributes->usage, mAudioAttributes->content_type, mAudioAttributes->flags,
1108 mAudioAttributes->tags);
1109
1110 if (mAudioOutput != 0) {
1111 mAudioOutput->setAudioAttributes(mAudioAttributes);
1112 }
1113 return NO_ERROR;
1114}
1115
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001116status_t MediaPlayerService::Client::setLooping(int loop)
1117{
Steve Block3856b092011-10-20 11:56:00 +01001118 ALOGV("[%d] setLooping(%d)", mConnId, loop);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001119 mLoop = loop;
1120 sp<MediaPlayerBase> p = getPlayer();
1121 if (p != 0) return p->setLooping(loop);
1122 return NO_ERROR;
1123}
1124
1125status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1126{
Steve Block3856b092011-10-20 11:56:00 +01001127 ALOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
John Grossman761defc2012-02-09 15:09:05 -08001128
1129 // for hardware output, call player instead
1130 sp<MediaPlayerBase> p = getPlayer();
1131 {
1132 Mutex::Autolock l(mLock);
1133 if (p != 0 && p->hardwareOutput()) {
1134 MediaPlayerHWInterface* hwp =
1135 reinterpret_cast<MediaPlayerHWInterface*>(p.get());
1136 return hwp->setVolume(leftVolume, rightVolume);
1137 } else {
1138 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1139 return NO_ERROR;
1140 }
1141 }
1142
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001143 return NO_ERROR;
1144}
1145
Eric Laurent2beeb502010-07-16 07:43:46 -07001146status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1147{
Steve Block3856b092011-10-20 11:56:00 +01001148 ALOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
Eric Laurent2beeb502010-07-16 07:43:46 -07001149 Mutex::Autolock l(mLock);
1150 if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1151 return NO_ERROR;
1152}
1153
1154status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1155{
Steve Block3856b092011-10-20 11:56:00 +01001156 ALOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
Eric Laurent2beeb502010-07-16 07:43:46 -07001157 Mutex::Autolock l(mLock);
1158 if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1159 return NO_ERROR;
1160}
Nicolas Catania48290382009-07-10 13:53:06 -07001161
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001162status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
Steve Block3856b092011-10-20 11:56:00 +01001163 ALOGV("[%d] setParameter(%d)", mConnId, key);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001164 switch (key) {
1165 case KEY_PARAMETER_AUDIO_ATTRIBUTES:
1166 {
1167 Mutex::Autolock l(mLock);
1168 return setAudioAttributes_l(request);
1169 }
1170 default:
1171 sp<MediaPlayerBase> p = getPlayer();
1172 if (p == 0) { return UNKNOWN_ERROR; }
1173 return p->setParameter(key, request);
1174 }
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001175}
1176
1177status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
Steve Block3856b092011-10-20 11:56:00 +01001178 ALOGV("[%d] getParameter(%d)", mConnId, key);
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001179 sp<MediaPlayerBase> p = getPlayer();
1180 if (p == 0) return UNKNOWN_ERROR;
1181 return p->getParameter(key, reply);
1182}
1183
John Grossmanc795b642012-02-22 15:38:35 -08001184status_t MediaPlayerService::Client::setRetransmitEndpoint(
1185 const struct sockaddr_in* endpoint) {
1186
1187 if (NULL != endpoint) {
1188 uint32_t a = ntohl(endpoint->sin_addr.s_addr);
1189 uint16_t p = ntohs(endpoint->sin_port);
1190 ALOGV("[%d] setRetransmitEndpoint(%u.%u.%u.%u:%hu)", mConnId,
1191 (a >> 24), (a >> 16) & 0xFF, (a >> 8) & 0xFF, (a & 0xFF), p);
1192 } else {
1193 ALOGV("[%d] setRetransmitEndpoint = <none>", mConnId);
1194 }
1195
1196 sp<MediaPlayerBase> p = getPlayer();
1197
1198 // Right now, the only valid time to set a retransmit endpoint is before
1199 // player selection has been made (since the presence or absence of a
1200 // retransmit endpoint is going to determine which player is selected during
1201 // setDataSource).
1202 if (p != 0) return INVALID_OPERATION;
1203
1204 if (NULL != endpoint) {
1205 mRetransmitEndpoint = *endpoint;
1206 mRetransmitEndpointValid = true;
1207 } else {
1208 mRetransmitEndpointValid = false;
1209 }
1210
1211 return NO_ERROR;
1212}
1213
John Grossman44a7e422012-06-21 17:29:24 -07001214status_t MediaPlayerService::Client::getRetransmitEndpoint(
1215 struct sockaddr_in* endpoint)
1216{
1217 if (NULL == endpoint)
1218 return BAD_VALUE;
1219
1220 sp<MediaPlayerBase> p = getPlayer();
1221
1222 if (p != NULL)
1223 return p->getRetransmitEndpoint(endpoint);
1224
1225 if (!mRetransmitEndpointValid)
1226 return NO_INIT;
1227
1228 *endpoint = mRetransmitEndpoint;
1229
1230 return NO_ERROR;
1231}
1232
Gloria Wangb483c472011-04-11 17:23:27 -07001233void MediaPlayerService::Client::notify(
1234 void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001235{
1236 Client* client = static_cast<Client*>(cookie);
James Dongb8a98252012-08-26 16:13:03 -07001237 if (client == NULL) {
1238 return;
1239 }
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001240
James Dongb8a98252012-08-26 16:13:03 -07001241 sp<IMediaPlayerClient> c;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001242 {
1243 Mutex::Autolock l(client->mLock);
James Dongb8a98252012-08-26 16:13:03 -07001244 c = client->mClient;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001245 if (msg == MEDIA_PLAYBACK_COMPLETE && client->mNextClient != NULL) {
John Grossmancb0b7552012-08-23 17:47:31 -07001246 if (client->mAudioOutput != NULL)
1247 client->mAudioOutput->switchToNextOutput();
Marco Nelissen6b74d672012-02-28 16:07:44 -08001248 client->mNextClient->start();
1249 client->mNextClient->mClient->notify(MEDIA_INFO, MEDIA_INFO_STARTED_AS_NEXT, 0, obj);
1250 }
1251 }
1252
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001253 if (MEDIA_INFO == msg &&
Nicolas Catania48290382009-07-10 13:53:06 -07001254 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikoa64c8c72009-07-20 15:07:26 -07001255 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania48290382009-07-10 13:53:06 -07001256
1257 if(client->shouldDropMetadata(metadata_type)) {
1258 return;
1259 }
1260
1261 // Update the list of metadata that have changed. getMetadata
1262 // also access mMetadataUpdated and clears it.
1263 client->addNewMetadataUpdate(metadata_type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001264 }
James Dongb8a98252012-08-26 16:13:03 -07001265
1266 if (c != NULL) {
1267 ALOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
1268 c->notify(msg, ext1, ext2, obj);
1269 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001270}
1271
Nicolas Catania48290382009-07-10 13:53:06 -07001272
nikoa64c8c72009-07-20 15:07:26 -07001273bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001274{
Nicolas Catania48290382009-07-10 13:53:06 -07001275 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001276
Nicolas Catania48290382009-07-10 13:53:06 -07001277 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001278 return true;
1279 }
1280
Nicolas Catania48290382009-07-10 13:53:06 -07001281 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001282 return false;
Nicolas Catania48290382009-07-10 13:53:06 -07001283 } else {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001284 return true;
1285 }
1286}
1287
Nicolas Catania48290382009-07-10 13:53:06 -07001288
nikoa64c8c72009-07-20 15:07:26 -07001289void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania48290382009-07-10 13:53:06 -07001290 Mutex::Autolock lock(mLock);
1291 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1292 mMetadataUpdated.add(metadata_type);
1293 }
1294}
1295
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001296#if CALLBACK_ANTAGONIZER
1297const int Antagonizer::interval = 10000; // 10 msecs
1298
1299Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1300 mExit(false), mActive(false), mClient(client), mCb(cb)
1301{
1302 createThread(callbackThread, this);
1303}
1304
1305void Antagonizer::kill()
1306{
1307 Mutex::Autolock _l(mLock);
1308 mActive = false;
1309 mExit = true;
1310 mCondition.wait(mLock);
1311}
1312
1313int Antagonizer::callbackThread(void* user)
1314{
Steve Blockb8a80522011-12-20 16:23:08 +00001315 ALOGD("Antagonizer started");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001316 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1317 while (!p->mExit) {
1318 if (p->mActive) {
Steve Block3856b092011-10-20 11:56:00 +01001319 ALOGV("send event");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001320 p->mCb(p->mClient, 0, 0, 0);
1321 }
1322 usleep(interval);
1323 }
1324 Mutex::Autolock _l(p->mLock);
1325 p->mCondition.signal();
Steve Blockb8a80522011-12-20 16:23:08 +00001326 ALOGD("Antagonizer stopped");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001327 return 0;
1328}
1329#endif
1330
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001331#undef LOG_TAG
1332#define LOG_TAG "AudioSink"
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001333MediaPlayerService::AudioOutput::AudioOutput(int sessionId, int uid, int pid,
1334 const audio_attributes_t* attr)
Andreas Huber20111aa2009-07-14 16:56:47 -07001335 : mCallback(NULL),
Eric Laurenta514bdb2010-06-21 09:27:30 -07001336 mCallbackCookie(NULL),
Marco Nelissen6b74d672012-02-28 16:07:44 -08001337 mCallbackData(NULL),
Marco Nelissen4110c102012-03-29 09:31:28 -07001338 mBytesWritten(0),
Andy Hungd1c74342015-07-07 16:54:23 -07001339 mStreamType(AUDIO_STREAM_MUSIC),
Andy Hungd1c74342015-07-07 16:54:23 -07001340 mLeftVolume(1.0),
1341 mRightVolume(1.0),
1342 mPlaybackRate(AUDIO_PLAYBACK_RATE_DEFAULT),
1343 mSampleRateHz(0),
1344 mMsecsPerFrame(0),
1345 mFrameSize(0),
Eric Laurent1948eb32012-04-13 16:50:19 -07001346 mSessionId(sessionId),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001347 mUid(uid),
Marco Nelissend457c972014-02-11 08:47:07 -08001348 mPid(pid),
Andy Hungd1c74342015-07-07 16:54:23 -07001349 mSendLevel(0.0),
1350 mAuxEffectId(0),
1351 mFlags(AUDIO_OUTPUT_FLAG_NONE)
1352{
Steve Block3856b092011-10-20 11:56:00 +01001353 ALOGV("AudioOutput(%d)", sessionId);
Eric Laurent43562692015-07-15 16:49:07 -07001354 if (attr != NULL) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001355 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1356 if (mAttributes != NULL) {
1357 memcpy(mAttributes, attr, sizeof(audio_attributes_t));
1358 mStreamType = audio_attributes_to_stream_type(attr);
1359 }
1360 } else {
1361 mAttributes = NULL;
Eric Laurent43562692015-07-15 16:49:07 -07001362 }
1363
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001364 setMinBufferCount();
1365}
1366
1367MediaPlayerService::AudioOutput::~AudioOutput()
1368{
1369 close();
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001370 free(mAttributes);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001371 delete mCallbackData;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001372}
1373
Andy Hungd1c74342015-07-07 16:54:23 -07001374//static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001375void MediaPlayerService::AudioOutput::setMinBufferCount()
1376{
1377 char value[PROPERTY_VALUE_MAX];
1378 if (property_get("ro.kernel.qemu", value, 0)) {
1379 mIsOnEmulator = true;
1380 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1381 }
1382}
1383
Andy Hungd1c74342015-07-07 16:54:23 -07001384// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001385bool MediaPlayerService::AudioOutput::isOnEmulator()
1386{
Andy Hungd1c74342015-07-07 16:54:23 -07001387 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001388 return mIsOnEmulator;
1389}
1390
Andy Hungd1c74342015-07-07 16:54:23 -07001391// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001392int MediaPlayerService::AudioOutput::getMinBufferCount()
1393{
Andy Hungd1c74342015-07-07 16:54:23 -07001394 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001395 return mMinBufferCount;
1396}
1397
1398ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1399{
Andy Hungd1c74342015-07-07 16:54:23 -07001400 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001401 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001402 return mTrack->frameCount() * mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001403}
1404
1405ssize_t MediaPlayerService::AudioOutput::frameCount() const
1406{
Andy Hungd1c74342015-07-07 16:54:23 -07001407 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001408 if (mTrack == 0) return NO_INIT;
1409 return mTrack->frameCount();
1410}
1411
1412ssize_t MediaPlayerService::AudioOutput::channelCount() const
1413{
Andy Hungd1c74342015-07-07 16:54:23 -07001414 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001415 if (mTrack == 0) return NO_INIT;
1416 return mTrack->channelCount();
1417}
1418
1419ssize_t MediaPlayerService::AudioOutput::frameSize() const
1420{
Andy Hungd1c74342015-07-07 16:54:23 -07001421 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001422 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001423 return mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001424}
1425
1426uint32_t MediaPlayerService::AudioOutput::latency () const
1427{
Andy Hungd1c74342015-07-07 16:54:23 -07001428 Mutex::Autolock lock(mLock);
Eric Laurentdb354e52012-03-05 17:27:11 -08001429 if (mTrack == 0) return 0;
1430 return mTrack->latency();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001431}
1432
1433float MediaPlayerService::AudioOutput::msecsPerFrame() const
1434{
Andy Hungd1c74342015-07-07 16:54:23 -07001435 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001436 return mMsecsPerFrame;
1437}
1438
Marco Nelissen4110c102012-03-29 09:31:28 -07001439status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position) const
Eric Laurent342e9cf2010-01-19 17:37:09 -08001440{
Andy Hungd1c74342015-07-07 16:54:23 -07001441 Mutex::Autolock lock(mLock);
Eric Laurent342e9cf2010-01-19 17:37:09 -08001442 if (mTrack == 0) return NO_INIT;
1443 return mTrack->getPosition(position);
1444}
1445
Lajos Molnar06ad1522014-08-28 07:27:44 -07001446status_t MediaPlayerService::AudioOutput::getTimestamp(AudioTimestamp &ts) const
1447{
Andy Hungd1c74342015-07-07 16:54:23 -07001448 Mutex::Autolock lock(mLock);
Lajos Molnar06ad1522014-08-28 07:27:44 -07001449 if (mTrack == 0) return NO_INIT;
1450 return mTrack->getTimestamp(ts);
1451}
1452
Marco Nelissen4110c102012-03-29 09:31:28 -07001453status_t MediaPlayerService::AudioOutput::getFramesWritten(uint32_t *frameswritten) const
1454{
Andy Hungd1c74342015-07-07 16:54:23 -07001455 Mutex::Autolock lock(mLock);
Marco Nelissen4110c102012-03-29 09:31:28 -07001456 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001457 *frameswritten = mBytesWritten / mFrameSize;
Marco Nelissen4110c102012-03-29 09:31:28 -07001458 return OK;
1459}
1460
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001461status_t MediaPlayerService::AudioOutput::setParameters(const String8& keyValuePairs)
1462{
Andy Hungd1c74342015-07-07 16:54:23 -07001463 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001464 if (mTrack == 0) return NO_INIT;
1465 return mTrack->setParameters(keyValuePairs);
1466}
1467
1468String8 MediaPlayerService::AudioOutput::getParameters(const String8& keys)
1469{
Andy Hungd1c74342015-07-07 16:54:23 -07001470 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001471 if (mTrack == 0) return String8::empty();
1472 return mTrack->getParameters(keys);
1473}
1474
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001475void MediaPlayerService::AudioOutput::setAudioAttributes(const audio_attributes_t * attributes) {
Andy Hungd1c74342015-07-07 16:54:23 -07001476 Mutex::Autolock lock(mLock);
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001477 if (attributes == NULL) {
1478 free(mAttributes);
1479 mAttributes = NULL;
1480 } else {
1481 if (mAttributes == NULL) {
1482 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1483 }
1484 memcpy(mAttributes, attributes, sizeof(audio_attributes_t));
Eric Laurent43562692015-07-15 16:49:07 -07001485 mStreamType = audio_attributes_to_stream_type(attributes);
1486 }
1487}
1488
1489void MediaPlayerService::AudioOutput::setAudioStreamType(audio_stream_type_t streamType)
1490{
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001491 Mutex::Autolock lock(mLock);
Eric Laurent43562692015-07-15 16:49:07 -07001492 // do not allow direct stream type modification if attributes have been set
1493 if (mAttributes == NULL) {
1494 mStreamType = streamType;
1495 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001496}
1497
Andy Hungd1c74342015-07-07 16:54:23 -07001498void MediaPlayerService::AudioOutput::deleteRecycledTrack_l()
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001499{
Andy Hungd1c74342015-07-07 16:54:23 -07001500 ALOGV("deleteRecycledTrack_l");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001501 if (mRecycledTrack != 0) {
1502
1503 if (mCallbackData != NULL) {
1504 mCallbackData->setOutput(NULL);
1505 mCallbackData->endTrackSwitch();
1506 }
1507
1508 if ((mRecycledTrack->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) {
1509 mRecycledTrack->flush();
1510 }
1511 // An offloaded track isn't flushed because the STREAM_END is reported
1512 // slightly prematurely to allow time for the gapless track switch
1513 // but this means that if we decide not to recycle the track there
1514 // could be a small amount of residual data still playing. We leave
1515 // AudioFlinger to drain the track.
1516
1517 mRecycledTrack.clear();
Andy Hungd1c74342015-07-07 16:54:23 -07001518 close_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001519 delete mCallbackData;
1520 mCallbackData = NULL;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001521 }
1522}
1523
Andy Hungd1c74342015-07-07 16:54:23 -07001524void MediaPlayerService::AudioOutput::close_l()
1525{
1526 mTrack.clear();
1527}
1528
Andreas Huber20111aa2009-07-14 16:56:47 -07001529status_t MediaPlayerService::AudioOutput::open(
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001530 uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
1531 audio_format_t format, int bufferCount,
Eric Laurent1948eb32012-04-13 16:50:19 -07001532 AudioCallback cb, void *cookie,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001533 audio_output_flags_t flags,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001534 const audio_offload_info_t *offloadInfo,
Andy Hung179652e2015-05-31 22:49:46 -07001535 bool doNotReconnect,
1536 uint32_t suggestedFrameCount)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001537{
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001538 ALOGV("open(%u, %d, 0x%x, 0x%x, %d, %d 0x%x)", sampleRate, channelCount, channelMask,
1539 format, bufferCount, mSessionId, flags);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001540
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001541 // offloading is only supported in callback mode for now.
1542 // offloadInfo must be present if offload flag is set
1543 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) &&
1544 ((cb == NULL) || (offloadInfo == NULL))) {
1545 return BAD_VALUE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001546 }
1547
Andy Hung179652e2015-05-31 22:49:46 -07001548 // compute frame count for the AudioTrack internal buffer
1549 size_t frameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001550 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1551 frameCount = 0; // AudioTrack will get frame count from AudioFlinger
1552 } else {
Andy Hung179652e2015-05-31 22:49:46 -07001553 // try to estimate the buffer processing fetch size from AudioFlinger.
1554 // framesPerBuffer is approximate and generally correct, except when it's not :-).
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001555 uint32_t afSampleRate;
1556 size_t afFrameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001557 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1558 return NO_INIT;
1559 }
1560 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1561 return NO_INIT;
1562 }
Andy Hung179652e2015-05-31 22:49:46 -07001563 const size_t framesPerBuffer =
1564 (unsigned long long)sampleRate * afFrameCount / afSampleRate;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001565
Andy Hung179652e2015-05-31 22:49:46 -07001566 if (bufferCount == 0) {
1567 // use suggestedFrameCount
1568 bufferCount = (suggestedFrameCount + framesPerBuffer - 1) / framesPerBuffer;
1569 }
1570 // Check argument bufferCount against the mininum buffer count
1571 if (bufferCount != 0 && bufferCount < mMinBufferCount) {
1572 ALOGV("bufferCount (%d) increased to %d", bufferCount, mMinBufferCount);
1573 bufferCount = mMinBufferCount;
1574 }
1575 // if frameCount is 0, then AudioTrack will get frame count from AudioFlinger
1576 // which will be the minimum size permitted.
1577 frameCount = bufferCount * framesPerBuffer;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001578 }
Andreas Huber20111aa2009-07-14 16:56:47 -07001579
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001580 if (channelMask == CHANNEL_MASK_USE_CHANNEL_ORDER) {
Glenn Kastenab334fd2012-03-14 12:56:06 -07001581 channelMask = audio_channel_out_mask_from_count(channelCount);
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001582 if (0 == channelMask) {
1583 ALOGE("open() error, can\'t derive mask for %d audio channels", channelCount);
1584 return NO_INIT;
1585 }
1586 }
Eric Laurent1948eb32012-04-13 16:50:19 -07001587
Andy Hungd1c74342015-07-07 16:54:23 -07001588 Mutex::Autolock lock(mLock);
Andy Hung179652e2015-05-31 22:49:46 -07001589 mCallback = cb;
1590 mCallbackCookie = cookie;
1591
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001592 // Check whether we can recycle the track
1593 bool reuse = false;
1594 bool bothOffloaded = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001595
Glenn Kasten2799d742013-05-30 14:33:29 -07001596 if (mRecycledTrack != 0) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001597 // check whether we are switching between two offloaded tracks
1598 bothOffloaded = (flags & mRecycledTrack->getFlags()
1599 & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0;
Marco Nelissen67295b52012-06-11 14:52:53 -07001600
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001601 // check if the existing track can be reused as-is, or if a new track needs to be created.
1602 reuse = true;
1603
Marco Nelissen67295b52012-06-11 14:52:53 -07001604 if ((mCallbackData == NULL && mCallback != NULL) ||
1605 (mCallbackData != NULL && mCallback == NULL)) {
1606 // recycled track uses callbacks but the caller wants to use writes, or vice versa
1607 ALOGV("can't chain callback and write");
1608 reuse = false;
1609 } else if ((mRecycledTrack->getSampleRate() != sampleRate) ||
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001610 (mRecycledTrack->channelCount() != (uint32_t)channelCount) ) {
1611 ALOGV("samplerate, channelcount differ: %u/%u Hz, %u/%d ch",
Marco Nelissen67295b52012-06-11 14:52:53 -07001612 mRecycledTrack->getSampleRate(), sampleRate,
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001613 mRecycledTrack->channelCount(), channelCount);
Marco Nelissen67295b52012-06-11 14:52:53 -07001614 reuse = false;
1615 } else if (flags != mFlags) {
1616 ALOGV("output flags differ %08x/%08x", flags, mFlags);
1617 reuse = false;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001618 } else if (mRecycledTrack->format() != format) {
1619 reuse = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001620 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001621 } else {
1622 ALOGV("no track available to recycle");
1623 }
1624
1625 ALOGV_IF(bothOffloaded, "both tracks offloaded");
1626
1627 // If we can't recycle and both tracks are offloaded
1628 // we must close the previous output before opening a new one
1629 if (bothOffloaded && !reuse) {
1630 ALOGV("both offloaded and not recycling");
Andy Hungd1c74342015-07-07 16:54:23 -07001631 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001632 }
1633
1634 sp<AudioTrack> t;
1635 CallbackData *newcbd = NULL;
1636
1637 // We don't attempt to create a new track if we are recycling an
1638 // offloaded track. But, if we are recycling a non-offloaded or we
1639 // are switching where one is offloaded and one isn't then we create
1640 // the new track in advance so that we can read additional stream info
1641
1642 if (!(reuse && bothOffloaded)) {
1643 ALOGV("creating new AudioTrack");
1644
1645 if (mCallback != NULL) {
1646 newcbd = new CallbackData(this);
1647 t = new AudioTrack(
1648 mStreamType,
1649 sampleRate,
1650 format,
1651 channelMask,
1652 frameCount,
1653 flags,
1654 CallbackWrapper,
1655 newcbd,
1656 0, // notification frames
1657 mSessionId,
1658 AudioTrack::TRANSFER_CALLBACK,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001659 offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -08001660 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001661 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001662 mAttributes,
1663 doNotReconnect);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001664 } else {
1665 t = new AudioTrack(
1666 mStreamType,
1667 sampleRate,
1668 format,
1669 channelMask,
1670 frameCount,
1671 flags,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001672 NULL, // callback
1673 NULL, // user data
1674 0, // notification frames
1675 mSessionId,
1676 AudioTrack::TRANSFER_DEFAULT,
1677 NULL, // offload info
Marco Nelissend457c972014-02-11 08:47:07 -08001678 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001679 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001680 mAttributes,
1681 doNotReconnect);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001682 }
1683
1684 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1685 ALOGE("Unable to create audio track");
1686 delete newcbd;
Glenn Kasten3e98ecd2015-05-18 13:13:24 -07001687 // t goes out of scope, so reference count drops to zero
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001688 return NO_INIT;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001689 } else {
1690 // successful AudioTrack initialization implies a legacy stream type was generated
1691 // from the audio attributes
1692 mStreamType = t->streamType();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001693 }
1694 }
1695
1696 if (reuse) {
1697 CHECK(mRecycledTrack != NULL);
1698
1699 if (!bothOffloaded) {
1700 if (mRecycledTrack->frameCount() != t->frameCount()) {
1701 ALOGV("framecount differs: %u/%u frames",
1702 mRecycledTrack->frameCount(), t->frameCount());
1703 reuse = false;
1704 }
1705 }
1706
Marco Nelissen67295b52012-06-11 14:52:53 -07001707 if (reuse) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001708 ALOGV("chaining to next output and recycling track");
Andy Hungd1c74342015-07-07 16:54:23 -07001709 close_l();
Marco Nelissen67295b52012-06-11 14:52:53 -07001710 mTrack = mRecycledTrack;
Glenn Kasten2799d742013-05-30 14:33:29 -07001711 mRecycledTrack.clear();
Marco Nelissen67295b52012-06-11 14:52:53 -07001712 if (mCallbackData != NULL) {
1713 mCallbackData->setOutput(this);
1714 }
Marco Nelissen67295b52012-06-11 14:52:53 -07001715 delete newcbd;
1716 return OK;
1717 }
Marco Nelissen67295b52012-06-11 14:52:53 -07001718 }
1719
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001720 // we're not going to reuse the track, unblock and flush it
1721 // this was done earlier if both tracks are offloaded
1722 if (!bothOffloaded) {
Andy Hungd1c74342015-07-07 16:54:23 -07001723 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001724 }
1725
1726 CHECK((t != NULL) && ((mCallback == NULL) || (newcbd != NULL)));
1727
Marco Nelissen67295b52012-06-11 14:52:53 -07001728 mCallbackData = newcbd;
Steve Block3856b092011-10-20 11:56:00 +01001729 ALOGV("setVolume");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001730 t->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07001731
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001732 mSampleRateHz = sampleRate;
Preetam Singh Ranawat2e17eef2015-08-12 12:11:46 -07001733 mFlags = flags;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001734 mMsecsPerFrame = 1E3f / (mPlaybackRate.mSpeed * sampleRate);
Andy Hungd1c74342015-07-07 16:54:23 -07001735 mFrameSize = t->frameSize();
Marco Nelissen99448602012-04-02 12:16:49 -07001736 uint32_t pos;
1737 if (t->getPosition(&pos) == OK) {
Andy Hungd1c74342015-07-07 16:54:23 -07001738 mBytesWritten = uint64_t(pos) * mFrameSize;
Marco Nelissen99448602012-04-02 12:16:49 -07001739 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001740 mTrack = t;
Eric Laurent2beeb502010-07-16 07:43:46 -07001741
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001742 status_t res = NO_ERROR;
Wei Jia0162d002015-06-09 11:59:33 -07001743 // Note some output devices may give us a direct track even though we don't specify it.
1744 // Example: Line application b/17459982.
Preetam Singh Ranawat2e17eef2015-08-12 12:11:46 -07001745 if ((t->getFlags() & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) {
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001746 res = t->setPlaybackRate(mPlaybackRate);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001747 if (res == NO_ERROR) {
1748 t->setAuxEffectSendLevel(mSendLevel);
1749 res = t->attachAuxEffect(mAuxEffectId);
1750 }
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001751 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001752 ALOGV("open() DONE status %d", res);
1753 return res;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001754}
1755
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001756status_t MediaPlayerService::AudioOutput::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001757{
Steve Block3856b092011-10-20 11:56:00 +01001758 ALOGV("start");
Andy Hungd1c74342015-07-07 16:54:23 -07001759 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001760 if (mCallbackData != NULL) {
1761 mCallbackData->endTrackSwitch();
1762 }
Glenn Kasten2799d742013-05-30 14:33:29 -07001763 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001764 mTrack->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07001765 mTrack->setAuxEffectSendLevel(mSendLevel);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001766 return mTrack->start();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001767 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001768 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001769}
1770
Marco Nelissen6b74d672012-02-28 16:07:44 -08001771void MediaPlayerService::AudioOutput::setNextOutput(const sp<AudioOutput>& nextOutput) {
Andy Hungd1c74342015-07-07 16:54:23 -07001772 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001773 mNextOutput = nextOutput;
1774}
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08001775
Marco Nelissen6b74d672012-02-28 16:07:44 -08001776void MediaPlayerService::AudioOutput::switchToNextOutput() {
1777 ALOGV("switchToNextOutput");
Andy Hungd1c74342015-07-07 16:54:23 -07001778
1779 // Try to acquire the callback lock before moving track (without incurring deadlock).
1780 const unsigned kMaxSwitchTries = 100;
1781 Mutex::Autolock lock(mLock);
1782 for (unsigned tries = 0;;) {
1783 if (mTrack == 0) {
1784 return;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001785 }
Andy Hungd1c74342015-07-07 16:54:23 -07001786 if (mNextOutput != NULL && mNextOutput != this) {
1787 if (mCallbackData != NULL) {
1788 // two alternative approaches
1789#if 1
1790 CallbackData *callbackData = mCallbackData;
1791 mLock.unlock();
1792 // proper acquisition sequence
1793 callbackData->lock();
1794 mLock.lock();
1795 // Caution: it is unlikely that someone deleted our callback or changed our target
1796 if (callbackData != mCallbackData || mNextOutput == NULL || mNextOutput == this) {
1797 // fatal if we are starved out.
1798 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
1799 "switchToNextOutput() cannot obtain correct lock sequence");
1800 callbackData->unlock();
1801 continue;
1802 }
1803 callbackData->mSwitching = true; // begin track switch
1804#else
1805 // tryBeginTrackSwitch() returns false if the callback has the lock.
1806 if (!mCallbackData->tryBeginTrackSwitch()) {
1807 // fatal if we are starved out.
1808 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
1809 "switchToNextOutput() cannot obtain callback lock");
1810 mLock.unlock();
1811 usleep(5 * 1000 /* usec */); // allow callback to use AudioOutput
1812 mLock.lock();
1813 continue;
1814 }
1815#endif
1816 }
1817
1818 Mutex::Autolock nextLock(mNextOutput->mLock);
1819
1820 // If the next output track is not NULL, then it has been
1821 // opened already for playback.
1822 // This is possible even without the next player being started,
1823 // for example, the next player could be prepared and seeked.
1824 //
1825 // Presuming it isn't advisable to force the track over.
1826 if (mNextOutput->mTrack == NULL) {
1827 ALOGD("Recycling track for gapless playback");
1828 delete mNextOutput->mCallbackData;
1829 mNextOutput->mCallbackData = mCallbackData;
1830 mNextOutput->mRecycledTrack = mTrack;
1831 mNextOutput->mSampleRateHz = mSampleRateHz;
1832 mNextOutput->mMsecsPerFrame = mMsecsPerFrame;
1833 mNextOutput->mBytesWritten = mBytesWritten;
1834 mNextOutput->mFlags = mFlags;
1835 mNextOutput->mFrameSize = mFrameSize;
1836 close_l();
1837 mCallbackData = NULL; // destruction handled by mNextOutput
1838 } else {
1839 ALOGW("Ignoring gapless playback because next player has already started");
1840 // remove track in case resource needed for future players.
1841 if (mCallbackData != NULL) {
1842 mCallbackData->endTrackSwitch(); // release lock for callbacks before close.
1843 }
1844 close_l();
1845 }
1846 }
1847 break;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001848 }
1849}
1850
Wei Jia7d3f4df2015-03-03 15:28:00 -08001851ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001852{
Andy Hungd1c74342015-07-07 16:54:23 -07001853 Mutex::Autolock lock(mLock);
Glenn Kastenadad3d72014-02-21 14:51:43 -08001854 LOG_ALWAYS_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
Andreas Huber20111aa2009-07-14 16:56:47 -07001855
Steve Block3856b092011-10-20 11:56:00 +01001856 //ALOGV("write(%p, %u)", buffer, size);
Glenn Kasten2799d742013-05-30 14:33:29 -07001857 if (mTrack != 0) {
Wei Jia7d3f4df2015-03-03 15:28:00 -08001858 ssize_t ret = mTrack->write(buffer, size, blocking);
Andy Hunga31335a2014-08-20 17:37:59 -07001859 if (ret >= 0) {
1860 mBytesWritten += ret;
1861 }
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001862 return ret;
1863 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001864 return NO_INIT;
1865}
1866
1867void MediaPlayerService::AudioOutput::stop()
1868{
Steve Block3856b092011-10-20 11:56:00 +01001869 ALOGV("stop");
Andy Hungd1c74342015-07-07 16:54:23 -07001870 Mutex::Autolock lock(mLock);
Andy Hungda17c042015-06-01 15:53:14 -07001871 mBytesWritten = 0;
Glenn Kasten2799d742013-05-30 14:33:29 -07001872 if (mTrack != 0) mTrack->stop();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001873}
1874
1875void MediaPlayerService::AudioOutput::flush()
1876{
Steve Block3856b092011-10-20 11:56:00 +01001877 ALOGV("flush");
Andy Hungd1c74342015-07-07 16:54:23 -07001878 Mutex::Autolock lock(mLock);
Andy Hungda17c042015-06-01 15:53:14 -07001879 mBytesWritten = 0;
Glenn Kasten2799d742013-05-30 14:33:29 -07001880 if (mTrack != 0) mTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001881}
1882
1883void MediaPlayerService::AudioOutput::pause()
1884{
Steve Block3856b092011-10-20 11:56:00 +01001885 ALOGV("pause");
Andy Hungd1c74342015-07-07 16:54:23 -07001886 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07001887 if (mTrack != 0) mTrack->pause();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001888}
1889
1890void MediaPlayerService::AudioOutput::close()
1891{
Steve Block3856b092011-10-20 11:56:00 +01001892 ALOGV("close");
Andy Hungd1c74342015-07-07 16:54:23 -07001893 Mutex::Autolock lock(mLock);
1894 close_l();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001895}
1896
1897void MediaPlayerService::AudioOutput::setVolume(float left, float right)
1898{
Steve Block3856b092011-10-20 11:56:00 +01001899 ALOGV("setVolume(%f, %f)", left, right);
Andy Hungd1c74342015-07-07 16:54:23 -07001900 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001901 mLeftVolume = left;
1902 mRightVolume = right;
Glenn Kasten2799d742013-05-30 14:33:29 -07001903 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001904 mTrack->setVolume(left, right);
1905 }
1906}
1907
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001908status_t MediaPlayerService::AudioOutput::setPlaybackRate(const AudioPlaybackRate &rate)
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001909{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001910 ALOGV("setPlaybackRate(%f %f %d %d)",
1911 rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Andy Hungd1c74342015-07-07 16:54:23 -07001912 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001913 if (mTrack == 0) {
1914 // remember rate so that we can set it when the track is opened
1915 mPlaybackRate = rate;
1916 return OK;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001917 }
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001918 status_t res = mTrack->setPlaybackRate(rate);
1919 if (res != NO_ERROR) {
1920 return res;
1921 }
1922 // rate.mSpeed is always greater than 0 if setPlaybackRate succeeded
1923 CHECK_GT(rate.mSpeed, 0.f);
1924 mPlaybackRate = rate;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001925 if (mSampleRateHz != 0) {
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001926 mMsecsPerFrame = 1E3f / (rate.mSpeed * mSampleRateHz);
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001927 }
1928 return res;
1929}
1930
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001931status_t MediaPlayerService::AudioOutput::getPlaybackRate(AudioPlaybackRate *rate)
1932{
1933 ALOGV("setPlaybackRate");
Andy Hungd1c74342015-07-07 16:54:23 -07001934 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001935 if (mTrack == 0) {
1936 return NO_INIT;
1937 }
1938 *rate = mTrack->getPlaybackRate();
1939 return NO_ERROR;
1940}
1941
Eric Laurent2beeb502010-07-16 07:43:46 -07001942status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
1943{
Steve Block3856b092011-10-20 11:56:00 +01001944 ALOGV("setAuxEffectSendLevel(%f)", level);
Andy Hungd1c74342015-07-07 16:54:23 -07001945 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07001946 mSendLevel = level;
Glenn Kasten2799d742013-05-30 14:33:29 -07001947 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07001948 return mTrack->setAuxEffectSendLevel(level);
1949 }
1950 return NO_ERROR;
1951}
1952
1953status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
1954{
Steve Block3856b092011-10-20 11:56:00 +01001955 ALOGV("attachAuxEffect(%d)", effectId);
Andy Hungd1c74342015-07-07 16:54:23 -07001956 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07001957 mAuxEffectId = effectId;
Glenn Kasten2799d742013-05-30 14:33:29 -07001958 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07001959 return mTrack->attachAuxEffect(effectId);
1960 }
1961 return NO_ERROR;
1962}
1963
Andreas Huber20111aa2009-07-14 16:56:47 -07001964// static
1965void MediaPlayerService::AudioOutput::CallbackWrapper(
Glenn Kastend217a8c2011-06-01 15:20:35 -07001966 int event, void *cookie, void *info) {
Steve Block3856b092011-10-20 11:56:00 +01001967 //ALOGV("callbackwrapper");
Marco Nelissen6b74d672012-02-28 16:07:44 -08001968 CallbackData *data = (CallbackData*)cookie;
Andy Hungd1c74342015-07-07 16:54:23 -07001969 // lock to ensure we aren't caught in the middle of a track switch.
Marco Nelissen6b74d672012-02-28 16:07:44 -08001970 data->lock();
1971 AudioOutput *me = data->getOutput();
Andreas Huber20111aa2009-07-14 16:56:47 -07001972 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001973 if (me == NULL) {
1974 // no output set, likely because the track was scheduled to be reused
1975 // by another player, but the format turned out to be incompatible.
1976 data->unlock();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001977 if (buffer != NULL) {
1978 buffer->size = 0;
1979 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001980 return;
1981 }
Andreas Huber20111aa2009-07-14 16:56:47 -07001982
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001983 switch(event) {
1984 case AudioTrack::EVENT_MORE_DATA: {
1985 size_t actualSize = (*me->mCallback)(
1986 me, buffer->raw, buffer->size, me->mCallbackCookie,
1987 CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08001988
Andy Hung719b46b2015-05-31 22:18:25 -07001989 // Log when no data is returned from the callback.
1990 // (1) We may have no data (especially with network streaming sources).
1991 // (2) We may have reached the EOS and the audio track is not stopped yet.
1992 // Note that AwesomePlayer/AudioPlayer will only return zero size when it reaches the EOS.
1993 // NuPlayerRenderer will return zero when it doesn't have data (it doesn't block to fill).
1994 //
1995 // This is a benign busy-wait, with the next data request generated 10 ms or more later;
1996 // nevertheless for power reasons, we don't want to see too many of these.
Andreas Huber2e8ffaf2010-02-18 16:45:13 -08001997
Andy Hung719b46b2015-05-31 22:18:25 -07001998 ALOGV_IF(actualSize == 0 && buffer->size > 0, "callbackwrapper: empty buffer returned");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001999
Andy Hung719b46b2015-05-31 22:18:25 -07002000 me->mBytesWritten += actualSize; // benign race with reader.
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002001 buffer->size = actualSize;
2002 } break;
2003
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002004 case AudioTrack::EVENT_STREAM_END:
Andy Hung719b46b2015-05-31 22:18:25 -07002005 // currently only occurs for offloaded callbacks
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002006 ALOGV("callbackwrapper: deliver EVENT_STREAM_END");
2007 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2008 me->mCallbackCookie, CB_EVENT_STREAM_END);
2009 break;
2010
2011 case AudioTrack::EVENT_NEW_IAUDIOTRACK :
2012 ALOGV("callbackwrapper: deliver EVENT_TEAR_DOWN");
2013 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2014 me->mCallbackCookie, CB_EVENT_TEAR_DOWN);
2015 break;
2016
Glenn Kasten421743b2015-06-01 08:18:08 -07002017 case AudioTrack::EVENT_UNDERRUN:
Andy Hung719b46b2015-05-31 22:18:25 -07002018 // This occurs when there is no data available, typically
Glenn Kasten421743b2015-06-01 08:18:08 -07002019 // when there is a failure to supply data to the AudioTrack. It can also
2020 // occur in non-offloaded mode when the audio device comes out of standby.
2021 //
Andy Hung719b46b2015-05-31 22:18:25 -07002022 // If an AudioTrack underruns it outputs silence. Since this happens suddenly
2023 // it may sound like an audible pop or glitch.
2024 //
2025 // The underrun event is sent once per track underrun; the condition is reset
2026 // when more data is sent to the AudioTrack.
Glenn Kasten421743b2015-06-01 08:18:08 -07002027 ALOGI("callbackwrapper: EVENT_UNDERRUN (discarded)");
2028 break;
2029
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002030 default:
2031 ALOGE("received unknown event type: %d inside CallbackWrapper !", event);
Andreas Huber51c1e0e2011-04-04 11:43:40 -07002032 }
2033
Marco Nelissen6b74d672012-02-28 16:07:44 -08002034 data->unlock();
Andreas Huber20111aa2009-07-14 16:56:47 -07002035}
2036
Marco Nelissen4110c102012-03-29 09:31:28 -07002037int MediaPlayerService::AudioOutput::getSessionId() const
Eric Laurent8c563ed2010-10-07 18:23:03 -07002038{
Andy Hungd1c74342015-07-07 16:54:23 -07002039 Mutex::Autolock lock(mLock);
Eric Laurent8c563ed2010-10-07 18:23:03 -07002040 return mSessionId;
2041}
2042
Eric Laurent6f59db12013-07-26 17:16:50 -07002043uint32_t MediaPlayerService::AudioOutput::getSampleRate() const
2044{
Andy Hungd1c74342015-07-07 16:54:23 -07002045 Mutex::Autolock lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -07002046 if (mTrack == 0) return 0;
2047 return mTrack->getSampleRate();
2048}
2049
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002050////////////////////////////////////////////////////////////////////////////////
2051
2052struct CallbackThread : public Thread {
2053 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
2054 MediaPlayerBase::AudioSink::AudioCallback cb,
2055 void *cookie);
2056
2057protected:
2058 virtual ~CallbackThread();
2059
2060 virtual bool threadLoop();
2061
2062private:
2063 wp<MediaPlayerBase::AudioSink> mSink;
2064 MediaPlayerBase::AudioSink::AudioCallback mCallback;
2065 void *mCookie;
2066 void *mBuffer;
2067 size_t mBufferSize;
2068
2069 CallbackThread(const CallbackThread &);
2070 CallbackThread &operator=(const CallbackThread &);
2071};
2072
2073CallbackThread::CallbackThread(
2074 const wp<MediaPlayerBase::AudioSink> &sink,
2075 MediaPlayerBase::AudioSink::AudioCallback cb,
2076 void *cookie)
2077 : mSink(sink),
2078 mCallback(cb),
2079 mCookie(cookie),
2080 mBuffer(NULL),
2081 mBufferSize(0) {
2082}
2083
2084CallbackThread::~CallbackThread() {
2085 if (mBuffer) {
2086 free(mBuffer);
2087 mBuffer = NULL;
2088 }
2089}
2090
2091bool CallbackThread::threadLoop() {
2092 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
2093 if (sink == NULL) {
2094 return false;
2095 }
2096
2097 if (mBuffer == NULL) {
2098 mBufferSize = sink->bufferSize();
2099 mBuffer = malloc(mBufferSize);
2100 }
2101
2102 size_t actualSize =
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002103 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie,
2104 MediaPlayerBase::AudioSink::CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002105
2106 if (actualSize > 0) {
2107 sink->write(mBuffer, actualSize);
Andy Hunga31335a2014-08-20 17:37:59 -07002108 // Could return false on sink->write() error or short count.
2109 // Not necessarily appropriate but would work for AudioCache behavior.
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002110 }
2111
2112 return true;
2113}
2114
2115////////////////////////////////////////////////////////////////////////////////
2116
Gloria Wang7cf180c2011-02-19 18:37:57 -08002117void MediaPlayerService::addBatteryData(uint32_t params)
2118{
2119 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002120
2121 int32_t time = systemTime() / 1000000L;
2122
2123 // change audio output devices. This notification comes from AudioFlinger
2124 if ((params & kBatteryDataSpeakerOn)
2125 || (params & kBatteryDataOtherAudioDeviceOn)) {
2126
2127 int deviceOn[NUM_AUDIO_DEVICES];
2128 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2129 deviceOn[i] = 0;
2130 }
2131
2132 if ((params & kBatteryDataSpeakerOn)
2133 && (params & kBatteryDataOtherAudioDeviceOn)) {
2134 deviceOn[SPEAKER_AND_OTHER] = 1;
2135 } else if (params & kBatteryDataSpeakerOn) {
2136 deviceOn[SPEAKER] = 1;
2137 } else {
2138 deviceOn[OTHER_AUDIO_DEVICE] = 1;
2139 }
2140
2141 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2142 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
2143
2144 if (mBatteryAudio.refCount > 0) { // if playing audio
2145 if (!deviceOn[i]) {
2146 mBatteryAudio.lastTime[i] += time;
2147 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2148 mBatteryAudio.lastTime[i] = 0;
2149 } else {
2150 mBatteryAudio.lastTime[i] = 0 - time;
2151 }
2152 }
2153
2154 mBatteryAudio.deviceOn[i] = deviceOn[i];
2155 }
2156 }
2157 return;
2158 }
2159
Marco Nelissenb7848f12014-12-04 08:57:56 -08002160 // an audio stream is started
Gloria Wang9ee159b2011-02-24 14:51:45 -08002161 if (params & kBatteryDataAudioFlingerStart) {
2162 // record the start time only if currently no other audio
2163 // is being played
2164 if (mBatteryAudio.refCount == 0) {
2165 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2166 if (mBatteryAudio.deviceOn[i]) {
2167 mBatteryAudio.lastTime[i] -= time;
2168 }
2169 }
2170 }
2171
2172 mBatteryAudio.refCount ++;
2173 return;
2174
2175 } else if (params & kBatteryDataAudioFlingerStop) {
2176 if (mBatteryAudio.refCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002177 ALOGW("Battery track warning: refCount is <= 0");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002178 return;
2179 }
2180
2181 // record the stop time only if currently this is the only
2182 // audio being played
2183 if (mBatteryAudio.refCount == 1) {
2184 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2185 if (mBatteryAudio.deviceOn[i]) {
2186 mBatteryAudio.lastTime[i] += time;
2187 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2188 mBatteryAudio.lastTime[i] = 0;
2189 }
2190 }
2191 }
2192
2193 mBatteryAudio.refCount --;
2194 return;
2195 }
2196
Gloria Wang7cf180c2011-02-19 18:37:57 -08002197 int uid = IPCThreadState::self()->getCallingUid();
2198 if (uid == AID_MEDIA) {
2199 return;
2200 }
2201 int index = mBatteryData.indexOfKey(uid);
Gloria Wang7cf180c2011-02-19 18:37:57 -08002202
2203 if (index < 0) { // create a new entry for this UID
2204 BatteryUsageInfo info;
2205 info.audioTotalTime = 0;
2206 info.videoTotalTime = 0;
2207 info.audioLastTime = 0;
2208 info.videoLastTime = 0;
2209 info.refCount = 0;
2210
Gloria Wang9ee159b2011-02-24 14:51:45 -08002211 if (mBatteryData.add(uid, info) == NO_MEMORY) {
Steve Block29357bc2012-01-06 19:20:56 +00002212 ALOGE("Battery track error: no memory for new app");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002213 return;
2214 }
Gloria Wang7cf180c2011-02-19 18:37:57 -08002215 }
2216
2217 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
2218
2219 if (params & kBatteryDataCodecStarted) {
2220 if (params & kBatteryDataTrackAudio) {
2221 info.audioLastTime -= time;
2222 info.refCount ++;
2223 }
2224 if (params & kBatteryDataTrackVideo) {
2225 info.videoLastTime -= time;
2226 info.refCount ++;
2227 }
2228 } else {
2229 if (info.refCount == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002230 ALOGW("Battery track warning: refCount is already 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002231 return;
2232 } else if (info.refCount < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00002233 ALOGE("Battery track error: refCount < 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002234 mBatteryData.removeItem(uid);
2235 return;
2236 }
2237
2238 if (params & kBatteryDataTrackAudio) {
2239 info.audioLastTime += time;
2240 info.refCount --;
2241 }
2242 if (params & kBatteryDataTrackVideo) {
2243 info.videoLastTime += time;
2244 info.refCount --;
2245 }
2246
2247 // no stream is being played by this UID
2248 if (info.refCount == 0) {
2249 info.audioTotalTime += info.audioLastTime;
2250 info.audioLastTime = 0;
2251 info.videoTotalTime += info.videoLastTime;
2252 info.videoLastTime = 0;
2253 }
2254 }
2255}
2256
2257status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
2258 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002259
2260 // audio output devices usage
2261 int32_t time = systemTime() / 1000000L; //in ms
2262 int32_t totalTime;
2263
2264 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2265 totalTime = mBatteryAudio.totalTime[i];
2266
2267 if (mBatteryAudio.deviceOn[i]
2268 && (mBatteryAudio.lastTime[i] != 0)) {
2269 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
2270 totalTime += tmpTime;
2271 }
2272
2273 reply->writeInt32(totalTime);
2274 // reset the total time
2275 mBatteryAudio.totalTime[i] = 0;
2276 }
2277
2278 // codec usage
Gloria Wang7cf180c2011-02-19 18:37:57 -08002279 BatteryUsageInfo info;
2280 int size = mBatteryData.size();
2281
2282 reply->writeInt32(size);
2283 int i = 0;
2284
2285 while (i < size) {
2286 info = mBatteryData.valueAt(i);
2287
2288 reply->writeInt32(mBatteryData.keyAt(i)); //UID
2289 reply->writeInt32(info.audioTotalTime);
2290 reply->writeInt32(info.videoTotalTime);
2291
2292 info.audioTotalTime = 0;
2293 info.videoTotalTime = 0;
2294
2295 // remove the UID entry where no stream is being played
2296 if (info.refCount <= 0) {
2297 mBatteryData.removeItemsAt(i);
2298 size --;
2299 i --;
2300 }
2301 i++;
2302 }
2303 return NO_ERROR;
2304}
nikoa64c8c72009-07-20 15:07:26 -07002305} // namespace android