blob: 7dd8c78c0b628da83bd8be12b9832a4a68854d9c [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>
Lajos Molnar01854c02016-01-12 16:22:42 -080060#include <media/stagefright/Utils.h>
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +010061#include <media/stagefright/foundation/ADebug.h>
Marco Nelissenf09611f2015-02-13 14:12:42 -080062#include <media/stagefright/foundation/ALooperRoster.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070063#include <mediautils/BatteryNotifier.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080064
Dima Zavin64760242011-05-11 14:15:23 -070065#include <system/audio.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070066
Gloria Wang7cf180c2011-02-19 18:37:57 -080067#include <private/android_filesystem_config.h>
68
James Dong559bf282012-03-28 10:29:14 -070069#include "ActivityManager.h"
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080070#include "MediaRecorderClient.h"
71#include "MediaPlayerService.h"
72#include "MetadataRetrieverClient.h"
John Grossman44a7e422012-06-21 17:29:24 -070073#include "MediaPlayerFactory.h"
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080074
Nicolas Catania14d27472009-07-13 14:37:49 -070075#include "TestPlayerStub.h"
Andreas Huberf9334412010-12-15 15:17:42 -080076#include "nuplayer/NuPlayerDriver.h"
Andreas Huber20111aa2009-07-14 16:56:47 -070077
Andreas Huber20111aa2009-07-14 16:56:47 -070078#include <OMX.h>
Nicolas Catania14d27472009-07-13 14:37:49 -070079
Andreas Hubered3e3e02012-03-26 11:13:27 -070080#include "Crypto.h"
Jeff Tinkercc82dc62013-02-08 10:18:35 -080081#include "Drm.h"
Andreas Huber59451f82012-09-18 10:36:32 -070082#include "HDCP.h"
Andreas Huberb7319a72013-05-29 14:20:52 -070083#include "HTTPBase.h"
Andreas Huber35213f12012-08-29 11:41:50 -070084#include "RemoteDisplay.h"
Andreas Hubered3e3e02012-03-26 11:13:27 -070085
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070086namespace {
nikoa64c8c72009-07-20 15:07:26 -070087using android::media::Metadata;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070088using android::status_t;
89using android::OK;
90using android::BAD_VALUE;
91using android::NOT_ENOUGH_DATA;
92using android::Parcel;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070093
94// Max number of entries in the filter.
95const int kMaxFilterSize = 64; // I pulled that out of thin air.
96
nikoa64c8c72009-07-20 15:07:26 -070097// FIXME: Move all the metadata related function in the Metadata.cpp
nikod608a812009-07-16 16:39:53 -070098
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070099
100// Unmarshall a filter from a Parcel.
101// Filter format in a parcel:
102//
103// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
104// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
105// | number of entries (n) |
106// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
107// | metadata type 1 |
108// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
109// | metadata type 2 |
110// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
111// ....
112// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
113// | metadata type n |
114// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
115//
116// @param p Parcel that should start with a filter.
117// @param[out] filter On exit contains the list of metadata type to be
118// filtered.
119// @param[out] status On exit contains the status code to be returned.
120// @return true if the parcel starts with a valid filter.
121bool unmarshallFilter(const Parcel& p,
nikoa64c8c72009-07-20 15:07:26 -0700122 Metadata::Filter *filter,
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700123 status_t *status)
124{
Nicolas Catania48290382009-07-10 13:53:06 -0700125 int32_t val;
126 if (p.readInt32(&val) != OK)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700127 {
Steve Block29357bc2012-01-06 19:20:56 +0000128 ALOGE("Failed to read filter's length");
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700129 *status = NOT_ENOUGH_DATA;
130 return false;
131 }
132
Nicolas Catania48290382009-07-10 13:53:06 -0700133 if( val > kMaxFilterSize || val < 0)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700134 {
Steve Block29357bc2012-01-06 19:20:56 +0000135 ALOGE("Invalid filter len %d", val);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700136 *status = BAD_VALUE;
137 return false;
138 }
139
Nicolas Catania48290382009-07-10 13:53:06 -0700140 const size_t num = val;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700141
142 filter->clear();
Nicolas Catania48290382009-07-10 13:53:06 -0700143 filter->setCapacity(num);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700144
nikoa64c8c72009-07-20 15:07:26 -0700145 size_t size = num * sizeof(Metadata::Type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700146
Nicolas Catania48290382009-07-10 13:53:06 -0700147
148 if (p.dataAvail() < size)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700149 {
Steve Block29357bc2012-01-06 19:20:56 +0000150 ALOGE("Filter too short expected %d but got %d", size, p.dataAvail());
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700151 *status = NOT_ENOUGH_DATA;
152 return false;
153 }
154
nikoa64c8c72009-07-20 15:07:26 -0700155 const Metadata::Type *data =
156 static_cast<const Metadata::Type*>(p.readInplace(size));
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700157
Nicolas Catania48290382009-07-10 13:53:06 -0700158 if (NULL == data)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700159 {
Steve Block29357bc2012-01-06 19:20:56 +0000160 ALOGE("Filter had no data");
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700161 *status = BAD_VALUE;
162 return false;
163 }
164
165 // TODO: The stl impl of vector would be more efficient here
166 // because it degenerates into a memcpy on pod types. Try to
167 // replace later or use stl::set.
Nicolas Catania48290382009-07-10 13:53:06 -0700168 for (size_t i = 0; i < num; ++i)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700169 {
Nicolas Catania48290382009-07-10 13:53:06 -0700170 filter->add(*data);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700171 ++data;
172 }
173 *status = OK;
174 return true;
175}
176
Nicolas Catania48290382009-07-10 13:53:06 -0700177// @param filter Of metadata type.
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700178// @param val To be searched.
179// @return true if a match was found.
nikoa64c8c72009-07-20 15:07:26 -0700180bool findMetadata(const Metadata::Filter& filter, const int32_t val)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700181{
182 // Deal with empty and ANY right away
183 if (filter.isEmpty()) return false;
nikoa64c8c72009-07-20 15:07:26 -0700184 if (filter[0] == Metadata::kAny) return true;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700185
Nicolas Catania48290382009-07-10 13:53:06 -0700186 return filter.indexOf(val) >= 0;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700187}
188
189} // anonymous namespace
190
191
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700192namespace {
193using android::Parcel;
194using android::String16;
195
196// marshalling tag indicating flattened utf16 tags
197// keep in sync with frameworks/base/media/java/android/media/AudioAttributes.java
198const int32_t kAudioAttributesMarshallTagFlattenTags = 1;
199
200// Audio attributes format in a parcel:
201//
202// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
203// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
204// | usage |
205// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
206// | content_type |
207// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Hyejin Kim4f418f92014-09-05 15:50:03 +0900208// | source |
209// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700210// | flags |
211// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
212// | kAudioAttributesMarshallTagFlattenTags | // ignore tags if not found
213// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
214// | flattened tags in UTF16 |
215// | ... |
216// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
217//
218// @param p Parcel that contains audio attributes.
219// @param[out] attributes On exit points to an initialized audio_attributes_t structure
220// @param[out] status On exit contains the status code to be returned.
221void unmarshallAudioAttributes(const Parcel& parcel, audio_attributes_t *attributes)
222{
223 attributes->usage = (audio_usage_t) parcel.readInt32();
224 attributes->content_type = (audio_content_type_t) parcel.readInt32();
Hyejin Kim4f418f92014-09-05 15:50:03 +0900225 attributes->source = (audio_source_t) parcel.readInt32();
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700226 attributes->flags = (audio_flags_mask_t) parcel.readInt32();
227 const bool hasFlattenedTag = (parcel.readInt32() == kAudioAttributesMarshallTagFlattenTags);
228 if (hasFlattenedTag) {
229 // the tags are UTF16, convert to UTF8
230 String16 tags = parcel.readString16();
231 ssize_t realTagSize = utf16_to_utf8_length(tags.string(), tags.size());
232 if (realTagSize <= 0) {
233 strcpy(attributes->tags, "");
234 } else {
235 // copy the flattened string into the attributes as the destination for the conversion:
236 // copying array size -1, array for tags was calloc'd, no need to NULL-terminate it
237 size_t tagSize = realTagSize > AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 ?
238 AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 : realTagSize;
239 utf16_to_utf8(tags.string(), tagSize, attributes->tags);
240 }
241 } else {
242 ALOGE("unmarshallAudioAttributes() received unflattened tags, ignoring tag values");
243 strcpy(attributes->tags, "");
244 }
245}
246} // anonymous namespace
247
248
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800249namespace android {
250
Marco Nelissenf09611f2015-02-13 14:12:42 -0800251extern ALooperRoster gLooperRoster;
252
253
Dave Burked681bbb2011-08-30 14:39:17 +0100254static bool checkPermission(const char* permissionString) {
Dave Burked681bbb2011-08-30 14:39:17 +0100255 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
256 bool ok = checkCallingPermission(String16(permissionString));
Steve Block29357bc2012-01-06 19:20:56 +0000257 if (!ok) ALOGE("Request requires %s", permissionString);
Dave Burked681bbb2011-08-30 14:39:17 +0100258 return ok;
259}
260
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800261// TODO: Find real cause of Audio/Video delay in PV framework and remove this workaround
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800262/* static */ int MediaPlayerService::AudioOutput::mMinBufferCount = 4;
263/* static */ bool MediaPlayerService::AudioOutput::mIsOnEmulator = false;
264
265void MediaPlayerService::instantiate() {
266 defaultServiceManager()->addService(
267 String16("media.player"), new MediaPlayerService());
268}
269
270MediaPlayerService::MediaPlayerService()
271{
Steve Block3856b092011-10-20 11:56:00 +0100272 ALOGV("MediaPlayerService created");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800273 mNextConnId = 1;
Gloria Wang9ee159b2011-02-24 14:51:45 -0800274
275 mBatteryAudio.refCount = 0;
276 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
277 mBatteryAudio.deviceOn[i] = 0;
278 mBatteryAudio.lastTime[i] = 0;
279 mBatteryAudio.totalTime[i] = 0;
280 }
281 // speaker is on by default
282 mBatteryAudio.deviceOn[SPEAKER] = 1;
John Grossman44a7e422012-06-21 17:29:24 -0700283
Chong Zhang0b30fd42014-07-23 14:46:05 -0700284 // reset battery stats
285 // if the mediaserver has crashed, battery stats could be left
286 // in bad state, reset the state upon service start.
Ruben Brunk99e69712015-05-26 17:25:07 -0700287 BatteryNotifier& notifier(BatteryNotifier::getInstance());
288 notifier.noteResetVideo();
289 notifier.noteResetAudio();
Chong Zhang0b30fd42014-07-23 14:46:05 -0700290
John Grossman44a7e422012-06-21 17:29:24 -0700291 MediaPlayerFactory::registerBuiltinFactories();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800292}
293
294MediaPlayerService::~MediaPlayerService()
295{
Steve Block3856b092011-10-20 11:56:00 +0100296 ALOGV("MediaPlayerService destroyed");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800297}
298
Svet Ganovbe71aa22015-04-28 12:06:02 -0700299sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(const String16 &opPackageName)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800300{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800301 pid_t pid = IPCThreadState::self()->getCallingPid();
Svet Ganovbe71aa22015-04-28 12:06:02 -0700302 sp<MediaRecorderClient> recorder = new MediaRecorderClient(this, pid, opPackageName);
Gloria Wangdac6a312009-10-29 15:46:37 -0700303 wp<MediaRecorderClient> w = recorder;
304 Mutex::Autolock lock(mLock);
305 mMediaRecorderClients.add(w);
Steve Block3856b092011-10-20 11:56:00 +0100306 ALOGV("Create new media recorder client from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800307 return recorder;
308}
309
Gloria Wangdac6a312009-10-29 15:46:37 -0700310void MediaPlayerService::removeMediaRecorderClient(wp<MediaRecorderClient> client)
311{
312 Mutex::Autolock lock(mLock);
313 mMediaRecorderClients.remove(client);
Steve Block3856b092011-10-20 11:56:00 +0100314 ALOGV("Delete media recorder client");
Gloria Wangdac6a312009-10-29 15:46:37 -0700315}
316
Glenn Kastenf37971f2012-02-03 11:06:53 -0800317sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800318{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800319 pid_t pid = IPCThreadState::self()->getCallingPid();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800320 sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
Steve Block3856b092011-10-20 11:56:00 +0100321 ALOGV("Create new media retriever from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800322 return retriever;
323}
324
Glenn Kastenf37971f2012-02-03 11:06:53 -0800325sp<IMediaPlayer> MediaPlayerService::create(const sp<IMediaPlayerClient>& client,
Dave Burked681bbb2011-08-30 14:39:17 +0100326 int audioSessionId)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800327{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800328 pid_t pid = IPCThreadState::self()->getCallingPid();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800329 int32_t connId = android_atomic_inc(&mNextConnId);
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700330
331 sp<Client> c = new Client(
332 this, pid, connId, client, audioSessionId,
333 IPCThreadState::self()->getCallingUid());
334
Steve Block3856b092011-10-20 11:56:00 +0100335 ALOGV("Create new client(%d) from pid %d, uid %d, ", connId, pid,
Dave Burked681bbb2011-08-30 14:39:17 +0100336 IPCThreadState::self()->getCallingUid());
337
338 wp<Client> w = c;
339 {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800340 Mutex::Autolock lock(mLock);
341 mClients.add(w);
342 }
Andreas Hubere2b10282010-11-23 11:41:34 -0800343 return c;
344}
345
Lajos Molnar1381d4b2014-08-07 15:18:35 -0700346sp<IMediaCodecList> MediaPlayerService::getCodecList() const {
347 return MediaCodecList::getLocalInstance();
348}
349
Andreas Huber318ad9c2009-10-15 13:46:54 -0700350sp<IOMX> MediaPlayerService::getOMX() {
351 Mutex::Autolock autoLock(mLock);
352
353 if (mOMX.get() == NULL) {
354 mOMX = new OMX;
355 }
356
357 return mOMX;
Andreas Huber20111aa2009-07-14 16:56:47 -0700358}
359
Andreas Hubered3e3e02012-03-26 11:13:27 -0700360sp<ICrypto> MediaPlayerService::makeCrypto() {
Andreas Huber1bd139a2012-04-03 14:19:20 -0700361 return new Crypto;
Andreas Hubered3e3e02012-03-26 11:13:27 -0700362}
363
Jeff Tinkercc82dc62013-02-08 10:18:35 -0800364sp<IDrm> MediaPlayerService::makeDrm() {
365 return new Drm;
366}
367
Andreas Huber279dcd82013-01-30 10:41:25 -0800368sp<IHDCP> MediaPlayerService::makeHDCP(bool createEncryptionModule) {
369 return new HDCP(createEncryptionModule);
Andreas Huber59451f82012-09-18 10:36:32 -0700370}
371
Jeff Brown2013a542012-09-04 21:38:42 -0700372sp<IRemoteDisplay> MediaPlayerService::listenForRemoteDisplay(
Svet Ganovbe71aa22015-04-28 12:06:02 -0700373 const String16 &opPackageName,
Jeff Brown2013a542012-09-04 21:38:42 -0700374 const sp<IRemoteDisplayClient>& client, const String8& iface) {
Jeff Brownaba33d52012-09-07 17:38:58 -0700375 if (!checkPermission("android.permission.CONTROL_WIFI_DISPLAY")) {
376 return NULL;
377 }
378
Svet Ganovbe71aa22015-04-28 12:06:02 -0700379 return new RemoteDisplay(opPackageName, client, iface.string());
Jeff Brown2013a542012-09-04 21:38:42 -0700380}
381
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800382status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
383{
384 const size_t SIZE = 256;
385 char buffer[SIZE];
386 String8 result;
387
388 result.append(" AudioOutput\n");
389 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n",
390 mStreamType, mLeftVolume, mRightVolume);
391 result.append(buffer);
392 snprintf(buffer, 255, " msec per frame(%f), latency (%d)\n",
Eric Laurentdb354e52012-03-05 17:27:11 -0800393 mMsecsPerFrame, (mTrack != 0) ? mTrack->latency() : -1);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800394 result.append(buffer);
Eric Laurent2beeb502010-07-16 07:43:46 -0700395 snprintf(buffer, 255, " aux effect id(%d), send level (%f)\n",
396 mAuxEffectId, mSendLevel);
397 result.append(buffer);
398
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800399 ::write(fd, result.string(), result.size());
400 if (mTrack != 0) {
401 mTrack->dump(fd, args);
402 }
403 return NO_ERROR;
404}
405
Lajos Molnar6d339f12015-04-17 16:15:53 -0700406status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800407{
408 const size_t SIZE = 256;
409 char buffer[SIZE];
410 String8 result;
411 result.append(" Client\n");
412 snprintf(buffer, 255, " pid(%d), connId(%d), status(%d), looping(%s)\n",
413 mPid, mConnId, mStatus, mLoop?"true": "false");
414 result.append(buffer);
415 write(fd, result.string(), result.size());
Andreas Hubera0b1d4b2011-06-07 15:52:25 -0700416 if (mPlayer != NULL) {
417 mPlayer->dump(fd, args);
418 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800419 if (mAudioOutput != 0) {
420 mAudioOutput->dump(fd, args);
421 }
422 write(fd, "\n", 1);
423 return NO_ERROR;
424}
425
Marco Nelissenf09611f2015-02-13 14:12:42 -0800426/**
427 * The only arguments this understands right now are -c, -von and -voff,
428 * which are parsed by ALooperRoster::dump()
429 */
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800430status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
431{
432 const size_t SIZE = 256;
433 char buffer[SIZE];
434 String8 result;
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530435 SortedVector< sp<Client> > clients; //to serialise the mutex unlock & client destruction.
436 SortedVector< sp<MediaRecorderClient> > mediaRecorderClients;
437
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800438 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
439 snprintf(buffer, SIZE, "Permission Denial: "
440 "can't dump MediaPlayerService from pid=%d, uid=%d\n",
441 IPCThreadState::self()->getCallingPid(),
442 IPCThreadState::self()->getCallingUid());
443 result.append(buffer);
444 } else {
445 Mutex::Autolock lock(mLock);
446 for (int i = 0, n = mClients.size(); i < n; ++i) {
447 sp<Client> c = mClients[i].promote();
448 if (c != 0) c->dump(fd, args);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530449 clients.add(c);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800450 }
James Dongb9141222010-07-08 11:16:11 -0700451 if (mMediaRecorderClients.size() == 0) {
452 result.append(" No media recorder client\n\n");
453 } else {
454 for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
455 sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
James Donge579e282011-10-18 22:29:20 -0700456 if (c != 0) {
457 snprintf(buffer, 255, " MediaRecorderClient pid(%d)\n", c->mPid);
458 result.append(buffer);
459 write(fd, result.string(), result.size());
460 result = "\n";
461 c->dump(fd, args);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530462 mediaRecorderClients.add(c);
James Donge579e282011-10-18 22:29:20 -0700463 }
James Dongb9141222010-07-08 11:16:11 -0700464 }
Gloria Wangdac6a312009-10-29 15:46:37 -0700465 }
466
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800467 result.append(" Files opened and/or mapped:\n");
Marco Nelissenf09611f2015-02-13 14:12:42 -0800468 snprintf(buffer, SIZE, "/proc/%d/maps", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800469 FILE *f = fopen(buffer, "r");
470 if (f) {
471 while (!feof(f)) {
472 fgets(buffer, SIZE, f);
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700473 if (strstr(buffer, " /storage/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800474 strstr(buffer, " /system/sounds/") ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700475 strstr(buffer, " /data/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800476 strstr(buffer, " /system/media/")) {
477 result.append(" ");
478 result.append(buffer);
479 }
480 }
481 fclose(f);
482 } else {
483 result.append("couldn't open ");
484 result.append(buffer);
485 result.append("\n");
486 }
487
Marco Nelissenf09611f2015-02-13 14:12:42 -0800488 snprintf(buffer, SIZE, "/proc/%d/fd", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800489 DIR *d = opendir(buffer);
490 if (d) {
491 struct dirent *ent;
492 while((ent = readdir(d)) != NULL) {
493 if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
Marco Nelissenf09611f2015-02-13 14:12:42 -0800494 snprintf(buffer, SIZE, "/proc/%d/fd/%s", getpid(), ent->d_name);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800495 struct stat s;
496 if (lstat(buffer, &s) == 0) {
497 if ((s.st_mode & S_IFMT) == S_IFLNK) {
498 char linkto[256];
499 int len = readlink(buffer, linkto, sizeof(linkto));
500 if(len > 0) {
501 if(len > 255) {
502 linkto[252] = '.';
503 linkto[253] = '.';
504 linkto[254] = '.';
505 linkto[255] = 0;
506 } else {
507 linkto[len] = 0;
508 }
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700509 if (strstr(linkto, "/storage/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800510 strstr(linkto, "/system/sounds/") == linkto ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700511 strstr(linkto, "/data/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800512 strstr(linkto, "/system/media/") == linkto) {
513 result.append(" ");
514 result.append(buffer);
515 result.append(" -> ");
516 result.append(linkto);
517 result.append("\n");
518 }
519 }
520 } else {
521 result.append(" unexpected type for ");
522 result.append(buffer);
523 result.append("\n");
524 }
525 }
526 }
527 }
528 closedir(d);
529 } else {
530 result.append("couldn't open ");
531 result.append(buffer);
532 result.append("\n");
533 }
534
Marco Nelissenf09611f2015-02-13 14:12:42 -0800535 gLooperRoster.dump(fd, args);
536
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800537 bool dumpMem = false;
538 for (size_t i = 0; i < args.size(); i++) {
539 if (args[i] == String16("-m")) {
540 dumpMem = true;
541 }
542 }
543 if (dumpMem) {
James Dong8635b7b2011-03-14 17:01:38 -0700544 dumpMemoryAddresses(fd);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800545 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800546 }
547 write(fd, result.string(), result.size());
548 return NO_ERROR;
549}
550
551void MediaPlayerService::removeClient(wp<Client> client)
552{
553 Mutex::Autolock lock(mLock);
554 mClients.remove(client);
555}
556
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700557MediaPlayerService::Client::Client(
558 const sp<MediaPlayerService>& service, pid_t pid,
559 int32_t connId, const sp<IMediaPlayerClient>& client,
560 int audioSessionId, uid_t uid)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800561{
Steve Block3856b092011-10-20 11:56:00 +0100562 ALOGV("Client(%d) constructor", connId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800563 mPid = pid;
564 mConnId = connId;
565 mService = service;
566 mClient = client;
567 mLoop = false;
568 mStatus = NO_INIT;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700569 mAudioSessionId = audioSessionId;
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700570 mUID = uid;
John Grossmanc795b642012-02-22 15:38:35 -0800571 mRetransmitEndpointValid = false;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700572 mAudioAttributes = NULL;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700573
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800574#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000575 ALOGD("create Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800576 mAntagonizer = new Antagonizer(notify, this);
577#endif
578}
579
580MediaPlayerService::Client::~Client()
581{
Steve Block3856b092011-10-20 11:56:00 +0100582 ALOGV("Client(%d) destructor pid = %d", mConnId, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800583 mAudioOutput.clear();
584 wp<Client> client(this);
585 disconnect();
586 mService->removeClient(client);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700587 if (mAudioAttributes != NULL) {
588 free(mAudioAttributes);
589 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800590}
591
592void MediaPlayerService::Client::disconnect()
593{
Steve Block3856b092011-10-20 11:56:00 +0100594 ALOGV("disconnect(%d) from pid %d", mConnId, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800595 // grab local reference and clear main reference to prevent future
596 // access to object
597 sp<MediaPlayerBase> p;
598 {
599 Mutex::Autolock l(mLock);
600 p = mPlayer;
beanzdcfefde2012-11-05 09:51:43 +0800601 mClient.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800602 }
Andreas Huber20111aa2009-07-14 16:56:47 -0700603
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800604 mPlayer.clear();
605
606 // clear the notification to prevent callbacks to dead client
607 // and reset the player. We assume the player will serialize
608 // access to itself if necessary.
609 if (p != 0) {
610 p->setNotifyCallback(0, 0);
611#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000612 ALOGD("kill Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800613 mAntagonizer->kill();
614#endif
615 p->reset();
616 }
617
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700618 disconnectNativeWindow();
619
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800620 IPCThreadState::self()->flushCommands();
621}
622
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800623sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
624{
625 // determine if we have the right player type
626 sp<MediaPlayerBase> p = mPlayer;
627 if ((p != NULL) && (p->playerType() != playerType)) {
Steve Block3856b092011-10-20 11:56:00 +0100628 ALOGV("delete player");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800629 p.clear();
630 }
631 if (p == NULL) {
Ronghua Wu68845c12015-07-21 09:50:48 -0700632 p = MediaPlayerFactory::createPlayer(playerType, this, notify, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800633 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700634
Jason Simmonsdb29e522011-08-12 13:46:55 -0700635 if (p != NULL) {
636 p->setUID(mUID);
637 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700638
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800639 return p;
640}
641
John Grossmanc795b642012-02-22 15:38:35 -0800642sp<MediaPlayerBase> MediaPlayerService::Client::setDataSource_pre(
643 player_type playerType)
644{
645 ALOGV("player type = %d", playerType);
646
647 // create the right type of player
648 sp<MediaPlayerBase> p = createPlayer(playerType);
649 if (p == NULL) {
650 return p;
651 }
652
653 if (!p->hardwareOutput()) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -0700654 Mutex::Autolock l(mLock);
Marco Nelissend457c972014-02-11 08:47:07 -0800655 mAudioOutput = new AudioOutput(mAudioSessionId, IPCThreadState::self()->getCallingUid(),
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700656 mPid, mAudioAttributes);
John Grossmanc795b642012-02-22 15:38:35 -0800657 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
658 }
659
660 return p;
661}
662
663void MediaPlayerService::Client::setDataSource_post(
664 const sp<MediaPlayerBase>& p,
665 status_t status)
666{
667 ALOGV(" setDataSource");
668 mStatus = status;
669 if (mStatus != OK) {
670 ALOGE(" error: %d", mStatus);
671 return;
672 }
673
674 // Set the re-transmission endpoint if one was chosen.
675 if (mRetransmitEndpointValid) {
676 mStatus = p->setRetransmitEndpoint(&mRetransmitEndpoint);
677 if (mStatus != NO_ERROR) {
678 ALOGE("setRetransmitEndpoint error: %d", mStatus);
679 }
680 }
681
682 if (mStatus == OK) {
683 mPlayer = p;
684 }
685}
686
Andreas Huber2db84552010-01-28 11:19:57 -0800687status_t MediaPlayerService::Client::setDataSource(
Andreas Huber1b86fe02014-01-29 11:13:26 -0800688 const sp<IMediaHTTPService> &httpService,
689 const char *url,
690 const KeyedVector<String8, String8> *headers)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800691{
Steve Block3856b092011-10-20 11:56:00 +0100692 ALOGV("setDataSource(%s)", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800693 if (url == NULL)
694 return UNKNOWN_ERROR;
695
Dave Burked681bbb2011-08-30 14:39:17 +0100696 if ((strncmp(url, "http://", 7) == 0) ||
697 (strncmp(url, "https://", 8) == 0) ||
698 (strncmp(url, "rtsp://", 7) == 0)) {
699 if (!checkPermission("android.permission.INTERNET")) {
700 return PERMISSION_DENIED;
701 }
702 }
703
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800704 if (strncmp(url, "content://", 10) == 0) {
705 // get a filedescriptor for the content Uri and
706 // pass it to the setDataSource(fd) method
707
708 String16 url16(url);
709 int fd = android::openContentProviderFile(url16);
710 if (fd < 0)
711 {
Steve Block29357bc2012-01-06 19:20:56 +0000712 ALOGE("Couldn't open fd for %s", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800713 return UNKNOWN_ERROR;
714 }
715 setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
716 close(fd);
717 return mStatus;
718 } else {
John Grossman44a7e422012-06-21 17:29:24 -0700719 player_type playerType = MediaPlayerFactory::getPlayerType(this, url);
John Grossmanc795b642012-02-22 15:38:35 -0800720 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
721 if (p == NULL) {
722 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800723 }
724
Andreas Huber1b86fe02014-01-29 11:13:26 -0800725 setDataSource_post(p, p->setDataSource(httpService, url, headers));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800726 return mStatus;
727 }
728}
729
730status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
731{
Steve Block3856b092011-10-20 11:56:00 +0100732 ALOGV("setDataSource fd=%d, offset=%lld, length=%lld", fd, offset, length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800733 struct stat sb;
734 int ret = fstat(fd, &sb);
735 if (ret != 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000736 ALOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800737 return UNKNOWN_ERROR;
738 }
739
Ying Wang5fde15d2015-04-20 22:13:22 -0700740 ALOGV("st_dev = %llu", static_cast<uint64_t>(sb.st_dev));
Steve Block3856b092011-10-20 11:56:00 +0100741 ALOGV("st_mode = %u", sb.st_mode);
Mark Salyzyn77342f72014-06-18 16:31:32 -0700742 ALOGV("st_uid = %lu", static_cast<unsigned long>(sb.st_uid));
743 ALOGV("st_gid = %lu", static_cast<unsigned long>(sb.st_gid));
Steve Block3856b092011-10-20 11:56:00 +0100744 ALOGV("st_size = %llu", sb.st_size);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800745
746 if (offset >= sb.st_size) {
Steve Block29357bc2012-01-06 19:20:56 +0000747 ALOGE("offset error");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800748 return UNKNOWN_ERROR;
749 }
750 if (offset + length > sb.st_size) {
751 length = sb.st_size - offset;
Steve Block3856b092011-10-20 11:56:00 +0100752 ALOGV("calculated length = %lld", length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800753 }
754
John Grossman44a7e422012-06-21 17:29:24 -0700755 player_type playerType = MediaPlayerFactory::getPlayerType(this,
756 fd,
757 offset,
758 length);
John Grossmanc795b642012-02-22 15:38:35 -0800759 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
760 if (p == NULL) {
761 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800762 }
763
764 // now set data source
John Grossmanc795b642012-02-22 15:38:35 -0800765 setDataSource_post(p, p->setDataSource(fd, offset, length));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800766 return mStatus;
767}
768
Andreas Hubere2b10282010-11-23 11:41:34 -0800769status_t MediaPlayerService::Client::setDataSource(
770 const sp<IStreamSource> &source) {
771 // create the right type of player
John Grossman44a7e422012-06-21 17:29:24 -0700772 player_type playerType = MediaPlayerFactory::getPlayerType(this, source);
John Grossmanc795b642012-02-22 15:38:35 -0800773 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
Andreas Hubere2b10282010-11-23 11:41:34 -0800774 if (p == NULL) {
775 return NO_INIT;
776 }
777
Andreas Hubere2b10282010-11-23 11:41:34 -0800778 // now set data source
John Grossmanc795b642012-02-22 15:38:35 -0800779 setDataSource_post(p, p->setDataSource(source));
Andreas Hubere2b10282010-11-23 11:41:34 -0800780 return mStatus;
781}
782
Chris Watkins99f31602015-03-20 13:06:33 -0700783status_t MediaPlayerService::Client::setDataSource(
784 const sp<IDataSource> &source) {
785 sp<DataSource> dataSource = DataSource::CreateFromIDataSource(source);
786 player_type playerType = MediaPlayerFactory::getPlayerType(this, dataSource);
787 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
788 if (p == NULL) {
789 return NO_INIT;
790 }
791 // now set data source
792 setDataSource_post(p, p->setDataSource(dataSource));
793 return mStatus;
794}
795
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700796void MediaPlayerService::Client::disconnectNativeWindow() {
797 if (mConnectedWindow != NULL) {
798 status_t err = native_window_api_disconnect(mConnectedWindow.get(),
799 NATIVE_WINDOW_API_MEDIA);
800
801 if (err != OK) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000802 ALOGW("native_window_api_disconnect returned an error: %s (%d)",
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700803 strerror(-err), err);
804 }
805 }
806 mConnectedWindow.clear();
807}
808
Glenn Kasten11731182011-02-08 17:26:17 -0800809status_t MediaPlayerService::Client::setVideoSurfaceTexture(
Andy McFadden484566c2012-12-18 09:46:54 -0800810 const sp<IGraphicBufferProducer>& bufferProducer)
Glenn Kasten11731182011-02-08 17:26:17 -0800811{
Andy McFadden484566c2012-12-18 09:46:54 -0800812 ALOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, bufferProducer.get());
Glenn Kasten11731182011-02-08 17:26:17 -0800813 sp<MediaPlayerBase> p = getPlayer();
814 if (p == 0) return UNKNOWN_ERROR;
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700815
Marco Nelissenf8880202014-11-14 07:58:25 -0800816 sp<IBinder> binder(IInterface::asBinder(bufferProducer));
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700817 if (mConnectedWindowBinder == binder) {
818 return OK;
819 }
820
821 sp<ANativeWindow> anw;
Andy McFadden484566c2012-12-18 09:46:54 -0800822 if (bufferProducer != NULL) {
Marco Nelissenee08f7e2013-09-16 13:30:01 -0700823 anw = new Surface(bufferProducer, true /* controlledByApp */);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700824 status_t err = native_window_api_connect(anw.get(),
825 NATIVE_WINDOW_API_MEDIA);
826
827 if (err != OK) {
Steve Block29357bc2012-01-06 19:20:56 +0000828 ALOGE("setVideoSurfaceTexture failed: %d", err);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700829 // Note that we must do the reset before disconnecting from the ANW.
830 // Otherwise queue/dequeue calls could be made on the disconnected
831 // ANW, which may result in errors.
832 reset();
833
834 disconnectNativeWindow();
835
836 return err;
837 }
838 }
839
Andy McFadden484566c2012-12-18 09:46:54 -0800840 // Note that we must set the player's new GraphicBufferProducer before
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700841 // disconnecting the old one. Otherwise queue/dequeue calls could be made
842 // on the disconnected ANW, which may result in errors.
Andy McFadden484566c2012-12-18 09:46:54 -0800843 status_t err = p->setVideoSurfaceTexture(bufferProducer);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700844
845 disconnectNativeWindow();
846
847 mConnectedWindow = anw;
848
849 if (err == OK) {
850 mConnectedWindowBinder = binder;
851 } else {
852 disconnectNativeWindow();
853 }
854
855 return err;
Glenn Kasten11731182011-02-08 17:26:17 -0800856}
857
Nicolas Catania1d187f12009-05-12 23:25:55 -0700858status_t MediaPlayerService::Client::invoke(const Parcel& request,
859 Parcel *reply)
860{
861 sp<MediaPlayerBase> p = getPlayer();
862 if (p == NULL) return UNKNOWN_ERROR;
863 return p->invoke(request, reply);
864}
865
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700866// This call doesn't need to access the native player.
867status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
868{
869 status_t status;
nikoa64c8c72009-07-20 15:07:26 -0700870 media::Metadata::Filter allow, drop;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700871
Nicolas Catania48290382009-07-10 13:53:06 -0700872 if (unmarshallFilter(filter, &allow, &status) &&
873 unmarshallFilter(filter, &drop, &status)) {
874 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700875
876 mMetadataAllow = allow;
877 mMetadataDrop = drop;
878 }
879 return status;
880}
881
Nicolas Catania48290382009-07-10 13:53:06 -0700882status_t MediaPlayerService::Client::getMetadata(
Mark Salyzyn77342f72014-06-18 16:31:32 -0700883 bool update_only, bool /*apply_filter*/, Parcel *reply)
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700884{
nikoa64c8c72009-07-20 15:07:26 -0700885 sp<MediaPlayerBase> player = getPlayer();
886 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania48290382009-07-10 13:53:06 -0700887
nikod608a812009-07-16 16:39:53 -0700888 status_t status;
889 // Placeholder for the return code, updated by the caller.
890 reply->writeInt32(-1);
891
nikoa64c8c72009-07-20 15:07:26 -0700892 media::Metadata::Filter ids;
Nicolas Catania48290382009-07-10 13:53:06 -0700893
894 // We don't block notifications while we fetch the data. We clear
895 // mMetadataUpdated first so we don't lose notifications happening
896 // during the rest of this call.
897 {
898 Mutex::Autolock lock(mLock);
899 if (update_only) {
nikod608a812009-07-16 16:39:53 -0700900 ids = mMetadataUpdated;
Nicolas Catania48290382009-07-10 13:53:06 -0700901 }
902 mMetadataUpdated.clear();
903 }
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700904
nikoa64c8c72009-07-20 15:07:26 -0700905 media::Metadata metadata(reply);
Nicolas Catania48290382009-07-10 13:53:06 -0700906
nikoa64c8c72009-07-20 15:07:26 -0700907 metadata.appendHeader();
908 status = player->getMetadata(ids, reply);
nikod608a812009-07-16 16:39:53 -0700909
910 if (status != OK) {
nikoa64c8c72009-07-20 15:07:26 -0700911 metadata.resetParcel();
Steve Block29357bc2012-01-06 19:20:56 +0000912 ALOGE("getMetadata failed %d", status);
nikod608a812009-07-16 16:39:53 -0700913 return status;
914 }
915
916 // FIXME: Implement filtering on the result. Not critical since
917 // filtering takes place on the update notifications already. This
918 // would be when all the metadata are fetch and a filter is set.
919
nikod608a812009-07-16 16:39:53 -0700920 // Everything is fine, update the metadata length.
nikoa64c8c72009-07-20 15:07:26 -0700921 metadata.updateLength();
nikod608a812009-07-16 16:39:53 -0700922 return OK;
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700923}
924
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800925status_t MediaPlayerService::Client::prepareAsync()
926{
Steve Block3856b092011-10-20 11:56:00 +0100927 ALOGV("[%d] prepareAsync", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800928 sp<MediaPlayerBase> p = getPlayer();
929 if (p == 0) return UNKNOWN_ERROR;
930 status_t ret = p->prepareAsync();
931#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000932 ALOGD("start Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800933 if (ret == NO_ERROR) mAntagonizer->start();
934#endif
935 return ret;
936}
937
938status_t MediaPlayerService::Client::start()
939{
Steve Block3856b092011-10-20 11:56:00 +0100940 ALOGV("[%d] start", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800941 sp<MediaPlayerBase> p = getPlayer();
942 if (p == 0) return UNKNOWN_ERROR;
943 p->setLooping(mLoop);
944 return p->start();
945}
946
947status_t MediaPlayerService::Client::stop()
948{
Steve Block3856b092011-10-20 11:56:00 +0100949 ALOGV("[%d] stop", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800950 sp<MediaPlayerBase> p = getPlayer();
951 if (p == 0) return UNKNOWN_ERROR;
952 return p->stop();
953}
954
955status_t MediaPlayerService::Client::pause()
956{
Steve Block3856b092011-10-20 11:56:00 +0100957 ALOGV("[%d] pause", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800958 sp<MediaPlayerBase> p = getPlayer();
959 if (p == 0) return UNKNOWN_ERROR;
960 return p->pause();
961}
962
963status_t MediaPlayerService::Client::isPlaying(bool* state)
964{
965 *state = false;
966 sp<MediaPlayerBase> p = getPlayer();
967 if (p == 0) return UNKNOWN_ERROR;
968 *state = p->isPlaying();
Steve Block3856b092011-10-20 11:56:00 +0100969 ALOGV("[%d] isPlaying: %d", mConnId, *state);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800970 return NO_ERROR;
971}
972
Lajos Molnar3a474aa2015-04-24 17:10:07 -0700973status_t MediaPlayerService::Client::setPlaybackSettings(const AudioPlaybackRate& rate)
Wei Jia98160162015-02-04 17:01:11 -0800974{
Lajos Molnar3a474aa2015-04-24 17:10:07 -0700975 ALOGV("[%d] setPlaybackSettings(%f, %f, %d, %d)",
976 mConnId, rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Wei Jia98160162015-02-04 17:01:11 -0800977 sp<MediaPlayerBase> p = getPlayer();
978 if (p == 0) return UNKNOWN_ERROR;
Lajos Molnar3a474aa2015-04-24 17:10:07 -0700979 return p->setPlaybackSettings(rate);
980}
981
982status_t MediaPlayerService::Client::getPlaybackSettings(AudioPlaybackRate* rate /* nonnull */)
983{
984 sp<MediaPlayerBase> p = getPlayer();
985 if (p == 0) return UNKNOWN_ERROR;
986 status_t ret = p->getPlaybackSettings(rate);
987 if (ret == NO_ERROR) {
988 ALOGV("[%d] getPlaybackSettings(%f, %f, %d, %d)",
989 mConnId, rate->mSpeed, rate->mPitch, rate->mFallbackMode, rate->mStretchMode);
990 } else {
991 ALOGV("[%d] getPlaybackSettings returned %d", mConnId, ret);
992 }
993 return ret;
994}
995
996status_t MediaPlayerService::Client::setSyncSettings(
997 const AVSyncSettings& sync, float videoFpsHint)
998{
999 ALOGV("[%d] setSyncSettings(%u, %u, %f, %f)",
1000 mConnId, sync.mSource, sync.mAudioAdjustMode, sync.mTolerance, videoFpsHint);
1001 sp<MediaPlayerBase> p = getPlayer();
1002 if (p == 0) return UNKNOWN_ERROR;
1003 return p->setSyncSettings(sync, videoFpsHint);
1004}
1005
1006status_t MediaPlayerService::Client::getSyncSettings(
1007 AVSyncSettings* sync /* nonnull */, float* videoFps /* nonnull */)
1008{
1009 sp<MediaPlayerBase> p = getPlayer();
1010 if (p == 0) return UNKNOWN_ERROR;
1011 status_t ret = p->getSyncSettings(sync, videoFps);
1012 if (ret == NO_ERROR) {
1013 ALOGV("[%d] getSyncSettings(%u, %u, %f, %f)",
1014 mConnId, sync->mSource, sync->mAudioAdjustMode, sync->mTolerance, *videoFps);
1015 } else {
1016 ALOGV("[%d] getSyncSettings returned %d", mConnId, ret);
1017 }
1018 return ret;
Wei Jia98160162015-02-04 17:01:11 -08001019}
1020
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001021status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
1022{
Steve Block3856b092011-10-20 11:56:00 +01001023 ALOGV("getCurrentPosition");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001024 sp<MediaPlayerBase> p = getPlayer();
1025 if (p == 0) return UNKNOWN_ERROR;
1026 status_t ret = p->getCurrentPosition(msec);
1027 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001028 ALOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001029 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001030 ALOGE("getCurrentPosition returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001031 }
1032 return ret;
1033}
1034
1035status_t MediaPlayerService::Client::getDuration(int *msec)
1036{
Steve Block3856b092011-10-20 11:56:00 +01001037 ALOGV("getDuration");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001038 sp<MediaPlayerBase> p = getPlayer();
1039 if (p == 0) return UNKNOWN_ERROR;
1040 status_t ret = p->getDuration(msec);
1041 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001042 ALOGV("[%d] getDuration = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001043 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001044 ALOGE("getDuration returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001045 }
1046 return ret;
1047}
1048
Marco Nelissen6b74d672012-02-28 16:07:44 -08001049status_t MediaPlayerService::Client::setNextPlayer(const sp<IMediaPlayer>& player) {
1050 ALOGV("setNextPlayer");
1051 Mutex::Autolock l(mLock);
1052 sp<Client> c = static_cast<Client*>(player.get());
1053 mNextClient = c;
John Grossman5f7e55e2012-08-24 14:47:25 -07001054
1055 if (c != NULL) {
1056 if (mAudioOutput != NULL) {
1057 mAudioOutput->setNextOutput(c->mAudioOutput);
1058 } else if ((mPlayer != NULL) && !mPlayer->hardwareOutput()) {
1059 ALOGE("no current audio output");
1060 }
1061
1062 if ((mPlayer != NULL) && (mNextClient->getPlayer() != NULL)) {
1063 mPlayer->setNextPlayer(mNextClient->getPlayer());
1064 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001065 }
John Grossman5f7e55e2012-08-24 14:47:25 -07001066
Marco Nelissen6b74d672012-02-28 16:07:44 -08001067 return OK;
1068}
1069
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001070status_t MediaPlayerService::Client::seekTo(int msec)
1071{
Steve Block3856b092011-10-20 11:56:00 +01001072 ALOGV("[%d] seekTo(%d)", mConnId, msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001073 sp<MediaPlayerBase> p = getPlayer();
1074 if (p == 0) return UNKNOWN_ERROR;
1075 return p->seekTo(msec);
1076}
1077
1078status_t MediaPlayerService::Client::reset()
1079{
Steve Block3856b092011-10-20 11:56:00 +01001080 ALOGV("[%d] reset", mConnId);
John Grossmanc795b642012-02-22 15:38:35 -08001081 mRetransmitEndpointValid = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001082 sp<MediaPlayerBase> p = getPlayer();
1083 if (p == 0) return UNKNOWN_ERROR;
1084 return p->reset();
1085}
1086
Glenn Kastenfff6d712012-01-12 16:38:12 -08001087status_t MediaPlayerService::Client::setAudioStreamType(audio_stream_type_t type)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001088{
Steve Block3856b092011-10-20 11:56:00 +01001089 ALOGV("[%d] setAudioStreamType(%d)", mConnId, type);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001090 // TODO: for hardware output, call player instead
1091 Mutex::Autolock l(mLock);
1092 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1093 return NO_ERROR;
1094}
1095
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001096status_t MediaPlayerService::Client::setAudioAttributes_l(const Parcel &parcel)
1097{
1098 if (mAudioAttributes != NULL) { free(mAudioAttributes); }
1099 mAudioAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001100 if (mAudioAttributes == NULL) {
1101 return NO_MEMORY;
1102 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001103 unmarshallAudioAttributes(parcel, mAudioAttributes);
1104
1105 ALOGV("setAudioAttributes_l() usage=%d content=%d flags=0x%x tags=%s",
1106 mAudioAttributes->usage, mAudioAttributes->content_type, mAudioAttributes->flags,
1107 mAudioAttributes->tags);
1108
1109 if (mAudioOutput != 0) {
1110 mAudioOutput->setAudioAttributes(mAudioAttributes);
1111 }
1112 return NO_ERROR;
1113}
1114
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001115status_t MediaPlayerService::Client::setLooping(int loop)
1116{
Steve Block3856b092011-10-20 11:56:00 +01001117 ALOGV("[%d] setLooping(%d)", mConnId, loop);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001118 mLoop = loop;
1119 sp<MediaPlayerBase> p = getPlayer();
1120 if (p != 0) return p->setLooping(loop);
1121 return NO_ERROR;
1122}
1123
1124status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1125{
Steve Block3856b092011-10-20 11:56:00 +01001126 ALOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
John Grossman761defc2012-02-09 15:09:05 -08001127
1128 // for hardware output, call player instead
1129 sp<MediaPlayerBase> p = getPlayer();
1130 {
1131 Mutex::Autolock l(mLock);
1132 if (p != 0 && p->hardwareOutput()) {
1133 MediaPlayerHWInterface* hwp =
1134 reinterpret_cast<MediaPlayerHWInterface*>(p.get());
1135 return hwp->setVolume(leftVolume, rightVolume);
1136 } else {
1137 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1138 return NO_ERROR;
1139 }
1140 }
1141
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001142 return NO_ERROR;
1143}
1144
Eric Laurent2beeb502010-07-16 07:43:46 -07001145status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1146{
Steve Block3856b092011-10-20 11:56:00 +01001147 ALOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
Eric Laurent2beeb502010-07-16 07:43:46 -07001148 Mutex::Autolock l(mLock);
1149 if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1150 return NO_ERROR;
1151}
1152
1153status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1154{
Steve Block3856b092011-10-20 11:56:00 +01001155 ALOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
Eric Laurent2beeb502010-07-16 07:43:46 -07001156 Mutex::Autolock l(mLock);
1157 if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1158 return NO_ERROR;
1159}
Nicolas Catania48290382009-07-10 13:53:06 -07001160
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001161status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
Steve Block3856b092011-10-20 11:56:00 +01001162 ALOGV("[%d] setParameter(%d)", mConnId, key);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001163 switch (key) {
1164 case KEY_PARAMETER_AUDIO_ATTRIBUTES:
1165 {
1166 Mutex::Autolock l(mLock);
1167 return setAudioAttributes_l(request);
1168 }
1169 default:
1170 sp<MediaPlayerBase> p = getPlayer();
1171 if (p == 0) { return UNKNOWN_ERROR; }
1172 return p->setParameter(key, request);
1173 }
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001174}
1175
1176status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
Steve Block3856b092011-10-20 11:56:00 +01001177 ALOGV("[%d] getParameter(%d)", mConnId, key);
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001178 sp<MediaPlayerBase> p = getPlayer();
1179 if (p == 0) return UNKNOWN_ERROR;
1180 return p->getParameter(key, reply);
1181}
1182
John Grossmanc795b642012-02-22 15:38:35 -08001183status_t MediaPlayerService::Client::setRetransmitEndpoint(
1184 const struct sockaddr_in* endpoint) {
1185
1186 if (NULL != endpoint) {
1187 uint32_t a = ntohl(endpoint->sin_addr.s_addr);
1188 uint16_t p = ntohs(endpoint->sin_port);
1189 ALOGV("[%d] setRetransmitEndpoint(%u.%u.%u.%u:%hu)", mConnId,
1190 (a >> 24), (a >> 16) & 0xFF, (a >> 8) & 0xFF, (a & 0xFF), p);
1191 } else {
1192 ALOGV("[%d] setRetransmitEndpoint = <none>", mConnId);
1193 }
1194
1195 sp<MediaPlayerBase> p = getPlayer();
1196
1197 // Right now, the only valid time to set a retransmit endpoint is before
1198 // player selection has been made (since the presence or absence of a
1199 // retransmit endpoint is going to determine which player is selected during
1200 // setDataSource).
1201 if (p != 0) return INVALID_OPERATION;
1202
1203 if (NULL != endpoint) {
1204 mRetransmitEndpoint = *endpoint;
1205 mRetransmitEndpointValid = true;
1206 } else {
1207 mRetransmitEndpointValid = false;
1208 }
1209
1210 return NO_ERROR;
1211}
1212
John Grossman44a7e422012-06-21 17:29:24 -07001213status_t MediaPlayerService::Client::getRetransmitEndpoint(
1214 struct sockaddr_in* endpoint)
1215{
1216 if (NULL == endpoint)
1217 return BAD_VALUE;
1218
1219 sp<MediaPlayerBase> p = getPlayer();
1220
1221 if (p != NULL)
1222 return p->getRetransmitEndpoint(endpoint);
1223
1224 if (!mRetransmitEndpointValid)
1225 return NO_INIT;
1226
1227 *endpoint = mRetransmitEndpoint;
1228
1229 return NO_ERROR;
1230}
1231
Gloria Wangb483c472011-04-11 17:23:27 -07001232void MediaPlayerService::Client::notify(
1233 void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001234{
1235 Client* client = static_cast<Client*>(cookie);
James Dongb8a98252012-08-26 16:13:03 -07001236 if (client == NULL) {
1237 return;
1238 }
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001239
James Dongb8a98252012-08-26 16:13:03 -07001240 sp<IMediaPlayerClient> c;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001241 {
1242 Mutex::Autolock l(client->mLock);
James Dongb8a98252012-08-26 16:13:03 -07001243 c = client->mClient;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001244 if (msg == MEDIA_PLAYBACK_COMPLETE && client->mNextClient != NULL) {
John Grossmancb0b7552012-08-23 17:47:31 -07001245 if (client->mAudioOutput != NULL)
1246 client->mAudioOutput->switchToNextOutput();
Marco Nelissen6b74d672012-02-28 16:07:44 -08001247 client->mNextClient->start();
1248 client->mNextClient->mClient->notify(MEDIA_INFO, MEDIA_INFO_STARTED_AS_NEXT, 0, obj);
1249 }
1250 }
1251
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001252 if (MEDIA_INFO == msg &&
Nicolas Catania48290382009-07-10 13:53:06 -07001253 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikoa64c8c72009-07-20 15:07:26 -07001254 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania48290382009-07-10 13:53:06 -07001255
1256 if(client->shouldDropMetadata(metadata_type)) {
1257 return;
1258 }
1259
1260 // Update the list of metadata that have changed. getMetadata
1261 // also access mMetadataUpdated and clears it.
1262 client->addNewMetadataUpdate(metadata_type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001263 }
James Dongb8a98252012-08-26 16:13:03 -07001264
1265 if (c != NULL) {
1266 ALOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
1267 c->notify(msg, ext1, ext2, obj);
1268 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001269}
1270
Nicolas Catania48290382009-07-10 13:53:06 -07001271
nikoa64c8c72009-07-20 15:07:26 -07001272bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001273{
Nicolas Catania48290382009-07-10 13:53:06 -07001274 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001275
Nicolas Catania48290382009-07-10 13:53:06 -07001276 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001277 return true;
1278 }
1279
Nicolas Catania48290382009-07-10 13:53:06 -07001280 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001281 return false;
Nicolas Catania48290382009-07-10 13:53:06 -07001282 } else {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001283 return true;
1284 }
1285}
1286
Nicolas Catania48290382009-07-10 13:53:06 -07001287
nikoa64c8c72009-07-20 15:07:26 -07001288void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania48290382009-07-10 13:53:06 -07001289 Mutex::Autolock lock(mLock);
1290 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1291 mMetadataUpdated.add(metadata_type);
1292 }
1293}
1294
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001295#if CALLBACK_ANTAGONIZER
1296const int Antagonizer::interval = 10000; // 10 msecs
1297
1298Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1299 mExit(false), mActive(false), mClient(client), mCb(cb)
1300{
1301 createThread(callbackThread, this);
1302}
1303
1304void Antagonizer::kill()
1305{
1306 Mutex::Autolock _l(mLock);
1307 mActive = false;
1308 mExit = true;
1309 mCondition.wait(mLock);
1310}
1311
1312int Antagonizer::callbackThread(void* user)
1313{
Steve Blockb8a80522011-12-20 16:23:08 +00001314 ALOGD("Antagonizer started");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001315 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1316 while (!p->mExit) {
1317 if (p->mActive) {
Steve Block3856b092011-10-20 11:56:00 +01001318 ALOGV("send event");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001319 p->mCb(p->mClient, 0, 0, 0);
1320 }
1321 usleep(interval);
1322 }
1323 Mutex::Autolock _l(p->mLock);
1324 p->mCondition.signal();
Steve Blockb8a80522011-12-20 16:23:08 +00001325 ALOGD("Antagonizer stopped");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001326 return 0;
1327}
1328#endif
1329
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001330#undef LOG_TAG
1331#define LOG_TAG "AudioSink"
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001332MediaPlayerService::AudioOutput::AudioOutput(int sessionId, int uid, int pid,
1333 const audio_attributes_t* attr)
Andreas Huber20111aa2009-07-14 16:56:47 -07001334 : mCallback(NULL),
Eric Laurenta514bdb2010-06-21 09:27:30 -07001335 mCallbackCookie(NULL),
Marco Nelissen6b74d672012-02-28 16:07:44 -08001336 mCallbackData(NULL),
Marco Nelissen4110c102012-03-29 09:31:28 -07001337 mBytesWritten(0),
Andy Hungd1c74342015-07-07 16:54:23 -07001338 mStreamType(AUDIO_STREAM_MUSIC),
Andy Hungd1c74342015-07-07 16:54:23 -07001339 mLeftVolume(1.0),
1340 mRightVolume(1.0),
1341 mPlaybackRate(AUDIO_PLAYBACK_RATE_DEFAULT),
1342 mSampleRateHz(0),
1343 mMsecsPerFrame(0),
1344 mFrameSize(0),
Eric Laurent1948eb32012-04-13 16:50:19 -07001345 mSessionId(sessionId),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001346 mUid(uid),
Marco Nelissend457c972014-02-11 08:47:07 -08001347 mPid(pid),
Andy Hungd1c74342015-07-07 16:54:23 -07001348 mSendLevel(0.0),
1349 mAuxEffectId(0),
1350 mFlags(AUDIO_OUTPUT_FLAG_NONE)
1351{
Steve Block3856b092011-10-20 11:56:00 +01001352 ALOGV("AudioOutput(%d)", sessionId);
Eric Laurent43562692015-07-15 16:49:07 -07001353 if (attr != NULL) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001354 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1355 if (mAttributes != NULL) {
1356 memcpy(mAttributes, attr, sizeof(audio_attributes_t));
1357 mStreamType = audio_attributes_to_stream_type(attr);
1358 }
1359 } else {
1360 mAttributes = NULL;
Eric Laurent43562692015-07-15 16:49:07 -07001361 }
1362
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001363 setMinBufferCount();
1364}
1365
1366MediaPlayerService::AudioOutput::~AudioOutput()
1367{
1368 close();
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001369 free(mAttributes);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001370 delete mCallbackData;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001371}
1372
Andy Hungd1c74342015-07-07 16:54:23 -07001373//static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001374void MediaPlayerService::AudioOutput::setMinBufferCount()
1375{
1376 char value[PROPERTY_VALUE_MAX];
1377 if (property_get("ro.kernel.qemu", value, 0)) {
1378 mIsOnEmulator = true;
1379 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1380 }
1381}
1382
Andy Hungd1c74342015-07-07 16:54:23 -07001383// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001384bool MediaPlayerService::AudioOutput::isOnEmulator()
1385{
Andy Hungd1c74342015-07-07 16:54:23 -07001386 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001387 return mIsOnEmulator;
1388}
1389
Andy Hungd1c74342015-07-07 16:54:23 -07001390// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001391int MediaPlayerService::AudioOutput::getMinBufferCount()
1392{
Andy Hungd1c74342015-07-07 16:54:23 -07001393 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001394 return mMinBufferCount;
1395}
1396
1397ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1398{
Andy Hungd1c74342015-07-07 16:54:23 -07001399 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001400 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001401 return mTrack->frameCount() * mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001402}
1403
1404ssize_t MediaPlayerService::AudioOutput::frameCount() const
1405{
Andy Hungd1c74342015-07-07 16:54:23 -07001406 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001407 if (mTrack == 0) return NO_INIT;
1408 return mTrack->frameCount();
1409}
1410
1411ssize_t MediaPlayerService::AudioOutput::channelCount() const
1412{
Andy Hungd1c74342015-07-07 16:54:23 -07001413 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001414 if (mTrack == 0) return NO_INIT;
1415 return mTrack->channelCount();
1416}
1417
1418ssize_t MediaPlayerService::AudioOutput::frameSize() const
1419{
Andy Hungd1c74342015-07-07 16:54:23 -07001420 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001421 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001422 return mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001423}
1424
1425uint32_t MediaPlayerService::AudioOutput::latency () const
1426{
Andy Hungd1c74342015-07-07 16:54:23 -07001427 Mutex::Autolock lock(mLock);
Eric Laurentdb354e52012-03-05 17:27:11 -08001428 if (mTrack == 0) return 0;
1429 return mTrack->latency();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001430}
1431
1432float MediaPlayerService::AudioOutput::msecsPerFrame() const
1433{
Andy Hungd1c74342015-07-07 16:54:23 -07001434 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001435 return mMsecsPerFrame;
1436}
1437
Marco Nelissen4110c102012-03-29 09:31:28 -07001438status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position) const
Eric Laurent342e9cf2010-01-19 17:37:09 -08001439{
Andy Hungd1c74342015-07-07 16:54:23 -07001440 Mutex::Autolock lock(mLock);
Eric Laurent342e9cf2010-01-19 17:37:09 -08001441 if (mTrack == 0) return NO_INIT;
1442 return mTrack->getPosition(position);
1443}
1444
Lajos Molnar06ad1522014-08-28 07:27:44 -07001445status_t MediaPlayerService::AudioOutput::getTimestamp(AudioTimestamp &ts) const
1446{
Andy Hungd1c74342015-07-07 16:54:23 -07001447 Mutex::Autolock lock(mLock);
Lajos Molnar06ad1522014-08-28 07:27:44 -07001448 if (mTrack == 0) return NO_INIT;
1449 return mTrack->getTimestamp(ts);
1450}
1451
Marco Nelissen4110c102012-03-29 09:31:28 -07001452status_t MediaPlayerService::AudioOutput::getFramesWritten(uint32_t *frameswritten) const
1453{
Andy Hungd1c74342015-07-07 16:54:23 -07001454 Mutex::Autolock lock(mLock);
Marco Nelissen4110c102012-03-29 09:31:28 -07001455 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001456 *frameswritten = mBytesWritten / mFrameSize;
Marco Nelissen4110c102012-03-29 09:31:28 -07001457 return OK;
1458}
1459
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001460status_t MediaPlayerService::AudioOutput::setParameters(const String8& keyValuePairs)
1461{
Andy Hungd1c74342015-07-07 16:54:23 -07001462 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001463 if (mTrack == 0) return NO_INIT;
1464 return mTrack->setParameters(keyValuePairs);
1465}
1466
1467String8 MediaPlayerService::AudioOutput::getParameters(const String8& keys)
1468{
Andy Hungd1c74342015-07-07 16:54:23 -07001469 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001470 if (mTrack == 0) return String8::empty();
1471 return mTrack->getParameters(keys);
1472}
1473
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001474void MediaPlayerService::AudioOutput::setAudioAttributes(const audio_attributes_t * attributes) {
Andy Hungd1c74342015-07-07 16:54:23 -07001475 Mutex::Autolock lock(mLock);
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001476 if (attributes == NULL) {
1477 free(mAttributes);
1478 mAttributes = NULL;
1479 } else {
1480 if (mAttributes == NULL) {
1481 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1482 }
1483 memcpy(mAttributes, attributes, sizeof(audio_attributes_t));
Eric Laurent43562692015-07-15 16:49:07 -07001484 mStreamType = audio_attributes_to_stream_type(attributes);
1485 }
1486}
1487
1488void MediaPlayerService::AudioOutput::setAudioStreamType(audio_stream_type_t streamType)
1489{
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001490 Mutex::Autolock lock(mLock);
Eric Laurent43562692015-07-15 16:49:07 -07001491 // do not allow direct stream type modification if attributes have been set
1492 if (mAttributes == NULL) {
1493 mStreamType = streamType;
1494 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001495}
1496
Andy Hungd1c74342015-07-07 16:54:23 -07001497void MediaPlayerService::AudioOutput::deleteRecycledTrack_l()
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001498{
Andy Hungd1c74342015-07-07 16:54:23 -07001499 ALOGV("deleteRecycledTrack_l");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001500 if (mRecycledTrack != 0) {
1501
1502 if (mCallbackData != NULL) {
1503 mCallbackData->setOutput(NULL);
1504 mCallbackData->endTrackSwitch();
1505 }
1506
1507 if ((mRecycledTrack->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) {
1508 mRecycledTrack->flush();
1509 }
1510 // An offloaded track isn't flushed because the STREAM_END is reported
1511 // slightly prematurely to allow time for the gapless track switch
1512 // but this means that if we decide not to recycle the track there
1513 // could be a small amount of residual data still playing. We leave
1514 // AudioFlinger to drain the track.
1515
1516 mRecycledTrack.clear();
Andy Hungd1c74342015-07-07 16:54:23 -07001517 close_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001518 delete mCallbackData;
1519 mCallbackData = NULL;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001520 }
1521}
1522
Andy Hungd1c74342015-07-07 16:54:23 -07001523void MediaPlayerService::AudioOutput::close_l()
1524{
1525 mTrack.clear();
1526}
1527
Andreas Huber20111aa2009-07-14 16:56:47 -07001528status_t MediaPlayerService::AudioOutput::open(
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001529 uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
1530 audio_format_t format, int bufferCount,
Eric Laurent1948eb32012-04-13 16:50:19 -07001531 AudioCallback cb, void *cookie,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001532 audio_output_flags_t flags,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001533 const audio_offload_info_t *offloadInfo,
Andy Hung179652e2015-05-31 22:49:46 -07001534 bool doNotReconnect,
1535 uint32_t suggestedFrameCount)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001536{
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001537 ALOGV("open(%u, %d, 0x%x, 0x%x, %d, %d 0x%x)", sampleRate, channelCount, channelMask,
1538 format, bufferCount, mSessionId, flags);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001539
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001540 // offloading is only supported in callback mode for now.
1541 // offloadInfo must be present if offload flag is set
1542 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) &&
1543 ((cb == NULL) || (offloadInfo == NULL))) {
1544 return BAD_VALUE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001545 }
1546
Andy Hung179652e2015-05-31 22:49:46 -07001547 // compute frame count for the AudioTrack internal buffer
1548 size_t frameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001549 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1550 frameCount = 0; // AudioTrack will get frame count from AudioFlinger
1551 } else {
Andy Hung179652e2015-05-31 22:49:46 -07001552 // try to estimate the buffer processing fetch size from AudioFlinger.
1553 // framesPerBuffer is approximate and generally correct, except when it's not :-).
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001554 uint32_t afSampleRate;
1555 size_t afFrameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001556 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1557 return NO_INIT;
1558 }
1559 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1560 return NO_INIT;
1561 }
Andy Hung179652e2015-05-31 22:49:46 -07001562 const size_t framesPerBuffer =
1563 (unsigned long long)sampleRate * afFrameCount / afSampleRate;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001564
Andy Hung179652e2015-05-31 22:49:46 -07001565 if (bufferCount == 0) {
1566 // use suggestedFrameCount
1567 bufferCount = (suggestedFrameCount + framesPerBuffer - 1) / framesPerBuffer;
1568 }
1569 // Check argument bufferCount against the mininum buffer count
1570 if (bufferCount != 0 && bufferCount < mMinBufferCount) {
1571 ALOGV("bufferCount (%d) increased to %d", bufferCount, mMinBufferCount);
1572 bufferCount = mMinBufferCount;
1573 }
1574 // if frameCount is 0, then AudioTrack will get frame count from AudioFlinger
1575 // which will be the minimum size permitted.
1576 frameCount = bufferCount * framesPerBuffer;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001577 }
Andreas Huber20111aa2009-07-14 16:56:47 -07001578
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001579 if (channelMask == CHANNEL_MASK_USE_CHANNEL_ORDER) {
Glenn Kastenab334fd2012-03-14 12:56:06 -07001580 channelMask = audio_channel_out_mask_from_count(channelCount);
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001581 if (0 == channelMask) {
1582 ALOGE("open() error, can\'t derive mask for %d audio channels", channelCount);
1583 return NO_INIT;
1584 }
1585 }
Eric Laurent1948eb32012-04-13 16:50:19 -07001586
Andy Hungd1c74342015-07-07 16:54:23 -07001587 Mutex::Autolock lock(mLock);
Andy Hung179652e2015-05-31 22:49:46 -07001588 mCallback = cb;
1589 mCallbackCookie = cookie;
1590
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001591 // Check whether we can recycle the track
1592 bool reuse = false;
1593 bool bothOffloaded = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001594
Glenn Kasten2799d742013-05-30 14:33:29 -07001595 if (mRecycledTrack != 0) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001596 // check whether we are switching between two offloaded tracks
1597 bothOffloaded = (flags & mRecycledTrack->getFlags()
1598 & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0;
Marco Nelissen67295b52012-06-11 14:52:53 -07001599
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001600 // check if the existing track can be reused as-is, or if a new track needs to be created.
1601 reuse = true;
1602
Marco Nelissen67295b52012-06-11 14:52:53 -07001603 if ((mCallbackData == NULL && mCallback != NULL) ||
1604 (mCallbackData != NULL && mCallback == NULL)) {
1605 // recycled track uses callbacks but the caller wants to use writes, or vice versa
1606 ALOGV("can't chain callback and write");
1607 reuse = false;
1608 } else if ((mRecycledTrack->getSampleRate() != sampleRate) ||
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001609 (mRecycledTrack->channelCount() != (uint32_t)channelCount) ) {
1610 ALOGV("samplerate, channelcount differ: %u/%u Hz, %u/%d ch",
Marco Nelissen67295b52012-06-11 14:52:53 -07001611 mRecycledTrack->getSampleRate(), sampleRate,
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001612 mRecycledTrack->channelCount(), channelCount);
Marco Nelissen67295b52012-06-11 14:52:53 -07001613 reuse = false;
1614 } else if (flags != mFlags) {
1615 ALOGV("output flags differ %08x/%08x", flags, mFlags);
1616 reuse = false;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001617 } else if (mRecycledTrack->format() != format) {
1618 reuse = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001619 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001620 } else {
1621 ALOGV("no track available to recycle");
1622 }
1623
1624 ALOGV_IF(bothOffloaded, "both tracks offloaded");
1625
1626 // If we can't recycle and both tracks are offloaded
1627 // we must close the previous output before opening a new one
1628 if (bothOffloaded && !reuse) {
1629 ALOGV("both offloaded and not recycling");
Andy Hungd1c74342015-07-07 16:54:23 -07001630 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001631 }
1632
1633 sp<AudioTrack> t;
1634 CallbackData *newcbd = NULL;
1635
1636 // We don't attempt to create a new track if we are recycling an
1637 // offloaded track. But, if we are recycling a non-offloaded or we
1638 // are switching where one is offloaded and one isn't then we create
1639 // the new track in advance so that we can read additional stream info
1640
1641 if (!(reuse && bothOffloaded)) {
1642 ALOGV("creating new AudioTrack");
1643
1644 if (mCallback != NULL) {
1645 newcbd = new CallbackData(this);
1646 t = new AudioTrack(
1647 mStreamType,
1648 sampleRate,
1649 format,
1650 channelMask,
1651 frameCount,
1652 flags,
1653 CallbackWrapper,
1654 newcbd,
1655 0, // notification frames
1656 mSessionId,
1657 AudioTrack::TRANSFER_CALLBACK,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001658 offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -08001659 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001660 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001661 mAttributes,
1662 doNotReconnect);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001663 } else {
1664 t = new AudioTrack(
1665 mStreamType,
1666 sampleRate,
1667 format,
1668 channelMask,
1669 frameCount,
1670 flags,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001671 NULL, // callback
1672 NULL, // user data
1673 0, // notification frames
1674 mSessionId,
1675 AudioTrack::TRANSFER_DEFAULT,
1676 NULL, // offload info
Marco Nelissend457c972014-02-11 08:47:07 -08001677 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001678 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001679 mAttributes,
1680 doNotReconnect);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001681 }
1682
1683 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1684 ALOGE("Unable to create audio track");
1685 delete newcbd;
Glenn Kasten3e98ecd2015-05-18 13:13:24 -07001686 // t goes out of scope, so reference count drops to zero
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001687 return NO_INIT;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001688 } else {
1689 // successful AudioTrack initialization implies a legacy stream type was generated
1690 // from the audio attributes
1691 mStreamType = t->streamType();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001692 }
1693 }
1694
1695 if (reuse) {
1696 CHECK(mRecycledTrack != NULL);
1697
1698 if (!bothOffloaded) {
1699 if (mRecycledTrack->frameCount() != t->frameCount()) {
1700 ALOGV("framecount differs: %u/%u frames",
1701 mRecycledTrack->frameCount(), t->frameCount());
1702 reuse = false;
1703 }
1704 }
1705
Marco Nelissen67295b52012-06-11 14:52:53 -07001706 if (reuse) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001707 ALOGV("chaining to next output and recycling track");
Andy Hungd1c74342015-07-07 16:54:23 -07001708 close_l();
Marco Nelissen67295b52012-06-11 14:52:53 -07001709 mTrack = mRecycledTrack;
Glenn Kasten2799d742013-05-30 14:33:29 -07001710 mRecycledTrack.clear();
Marco Nelissen67295b52012-06-11 14:52:53 -07001711 if (mCallbackData != NULL) {
1712 mCallbackData->setOutput(this);
1713 }
Marco Nelissen67295b52012-06-11 14:52:53 -07001714 delete newcbd;
1715 return OK;
1716 }
Marco Nelissen67295b52012-06-11 14:52:53 -07001717 }
1718
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001719 // we're not going to reuse the track, unblock and flush it
1720 // this was done earlier if both tracks are offloaded
1721 if (!bothOffloaded) {
Andy Hungd1c74342015-07-07 16:54:23 -07001722 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001723 }
1724
1725 CHECK((t != NULL) && ((mCallback == NULL) || (newcbd != NULL)));
1726
Marco Nelissen67295b52012-06-11 14:52:53 -07001727 mCallbackData = newcbd;
Steve Block3856b092011-10-20 11:56:00 +01001728 ALOGV("setVolume");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001729 t->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07001730
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001731 mSampleRateHz = sampleRate;
Preetam Singh Ranawat2e17eef2015-08-12 12:11:46 -07001732 mFlags = flags;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001733 mMsecsPerFrame = 1E3f / (mPlaybackRate.mSpeed * sampleRate);
Andy Hungd1c74342015-07-07 16:54:23 -07001734 mFrameSize = t->frameSize();
Marco Nelissen99448602012-04-02 12:16:49 -07001735 uint32_t pos;
1736 if (t->getPosition(&pos) == OK) {
Andy Hungd1c74342015-07-07 16:54:23 -07001737 mBytesWritten = uint64_t(pos) * mFrameSize;
Marco Nelissen99448602012-04-02 12:16:49 -07001738 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001739 mTrack = t;
Eric Laurent2beeb502010-07-16 07:43:46 -07001740
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001741 status_t res = NO_ERROR;
Wei Jia0162d002015-06-09 11:59:33 -07001742 // Note some output devices may give us a direct track even though we don't specify it.
1743 // Example: Line application b/17459982.
Preetam Singh Ranawat2e17eef2015-08-12 12:11:46 -07001744 if ((t->getFlags() & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) {
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001745 res = t->setPlaybackRate(mPlaybackRate);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001746 if (res == NO_ERROR) {
1747 t->setAuxEffectSendLevel(mSendLevel);
1748 res = t->attachAuxEffect(mAuxEffectId);
1749 }
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001750 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001751 ALOGV("open() DONE status %d", res);
1752 return res;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001753}
1754
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001755status_t MediaPlayerService::AudioOutput::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001756{
Steve Block3856b092011-10-20 11:56:00 +01001757 ALOGV("start");
Andy Hungd1c74342015-07-07 16:54:23 -07001758 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001759 if (mCallbackData != NULL) {
1760 mCallbackData->endTrackSwitch();
1761 }
Glenn Kasten2799d742013-05-30 14:33:29 -07001762 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001763 mTrack->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07001764 mTrack->setAuxEffectSendLevel(mSendLevel);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001765 return mTrack->start();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001766 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001767 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001768}
1769
Marco Nelissen6b74d672012-02-28 16:07:44 -08001770void MediaPlayerService::AudioOutput::setNextOutput(const sp<AudioOutput>& nextOutput) {
Andy Hungd1c74342015-07-07 16:54:23 -07001771 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001772 mNextOutput = nextOutput;
1773}
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08001774
Marco Nelissen6b74d672012-02-28 16:07:44 -08001775void MediaPlayerService::AudioOutput::switchToNextOutput() {
1776 ALOGV("switchToNextOutput");
Andy Hungd1c74342015-07-07 16:54:23 -07001777
1778 // Try to acquire the callback lock before moving track (without incurring deadlock).
1779 const unsigned kMaxSwitchTries = 100;
1780 Mutex::Autolock lock(mLock);
1781 for (unsigned tries = 0;;) {
1782 if (mTrack == 0) {
1783 return;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001784 }
Andy Hungd1c74342015-07-07 16:54:23 -07001785 if (mNextOutput != NULL && mNextOutput != this) {
1786 if (mCallbackData != NULL) {
1787 // two alternative approaches
1788#if 1
1789 CallbackData *callbackData = mCallbackData;
1790 mLock.unlock();
1791 // proper acquisition sequence
1792 callbackData->lock();
1793 mLock.lock();
1794 // Caution: it is unlikely that someone deleted our callback or changed our target
1795 if (callbackData != mCallbackData || mNextOutput == NULL || mNextOutput == this) {
1796 // fatal if we are starved out.
1797 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
1798 "switchToNextOutput() cannot obtain correct lock sequence");
1799 callbackData->unlock();
1800 continue;
1801 }
1802 callbackData->mSwitching = true; // begin track switch
1803#else
1804 // tryBeginTrackSwitch() returns false if the callback has the lock.
1805 if (!mCallbackData->tryBeginTrackSwitch()) {
1806 // fatal if we are starved out.
1807 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
1808 "switchToNextOutput() cannot obtain callback lock");
1809 mLock.unlock();
1810 usleep(5 * 1000 /* usec */); // allow callback to use AudioOutput
1811 mLock.lock();
1812 continue;
1813 }
1814#endif
1815 }
1816
1817 Mutex::Autolock nextLock(mNextOutput->mLock);
1818
1819 // If the next output track is not NULL, then it has been
1820 // opened already for playback.
1821 // This is possible even without the next player being started,
1822 // for example, the next player could be prepared and seeked.
1823 //
1824 // Presuming it isn't advisable to force the track over.
1825 if (mNextOutput->mTrack == NULL) {
1826 ALOGD("Recycling track for gapless playback");
1827 delete mNextOutput->mCallbackData;
1828 mNextOutput->mCallbackData = mCallbackData;
1829 mNextOutput->mRecycledTrack = mTrack;
1830 mNextOutput->mSampleRateHz = mSampleRateHz;
1831 mNextOutput->mMsecsPerFrame = mMsecsPerFrame;
1832 mNextOutput->mBytesWritten = mBytesWritten;
1833 mNextOutput->mFlags = mFlags;
1834 mNextOutput->mFrameSize = mFrameSize;
1835 close_l();
1836 mCallbackData = NULL; // destruction handled by mNextOutput
1837 } else {
1838 ALOGW("Ignoring gapless playback because next player has already started");
1839 // remove track in case resource needed for future players.
1840 if (mCallbackData != NULL) {
1841 mCallbackData->endTrackSwitch(); // release lock for callbacks before close.
1842 }
1843 close_l();
1844 }
1845 }
1846 break;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001847 }
1848}
1849
Wei Jia7d3f4df2015-03-03 15:28:00 -08001850ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001851{
Andy Hungd1c74342015-07-07 16:54:23 -07001852 Mutex::Autolock lock(mLock);
Glenn Kastenadad3d72014-02-21 14:51:43 -08001853 LOG_ALWAYS_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
Andreas Huber20111aa2009-07-14 16:56:47 -07001854
Steve Block3856b092011-10-20 11:56:00 +01001855 //ALOGV("write(%p, %u)", buffer, size);
Glenn Kasten2799d742013-05-30 14:33:29 -07001856 if (mTrack != 0) {
Wei Jia7d3f4df2015-03-03 15:28:00 -08001857 ssize_t ret = mTrack->write(buffer, size, blocking);
Andy Hunga31335a2014-08-20 17:37:59 -07001858 if (ret >= 0) {
1859 mBytesWritten += ret;
1860 }
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001861 return ret;
1862 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001863 return NO_INIT;
1864}
1865
1866void MediaPlayerService::AudioOutput::stop()
1867{
Steve Block3856b092011-10-20 11:56:00 +01001868 ALOGV("stop");
Andy Hungd1c74342015-07-07 16:54:23 -07001869 Mutex::Autolock lock(mLock);
Andy Hungda17c042015-06-01 15:53:14 -07001870 mBytesWritten = 0;
Glenn Kasten2799d742013-05-30 14:33:29 -07001871 if (mTrack != 0) mTrack->stop();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001872}
1873
1874void MediaPlayerService::AudioOutput::flush()
1875{
Steve Block3856b092011-10-20 11:56:00 +01001876 ALOGV("flush");
Andy Hungd1c74342015-07-07 16:54:23 -07001877 Mutex::Autolock lock(mLock);
Andy Hungda17c042015-06-01 15:53:14 -07001878 mBytesWritten = 0;
Glenn Kasten2799d742013-05-30 14:33:29 -07001879 if (mTrack != 0) mTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001880}
1881
1882void MediaPlayerService::AudioOutput::pause()
1883{
Steve Block3856b092011-10-20 11:56:00 +01001884 ALOGV("pause");
Andy Hungd1c74342015-07-07 16:54:23 -07001885 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07001886 if (mTrack != 0) mTrack->pause();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001887}
1888
1889void MediaPlayerService::AudioOutput::close()
1890{
Steve Block3856b092011-10-20 11:56:00 +01001891 ALOGV("close");
Andy Hungd1c74342015-07-07 16:54:23 -07001892 Mutex::Autolock lock(mLock);
1893 close_l();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001894}
1895
1896void MediaPlayerService::AudioOutput::setVolume(float left, float right)
1897{
Steve Block3856b092011-10-20 11:56:00 +01001898 ALOGV("setVolume(%f, %f)", left, right);
Andy Hungd1c74342015-07-07 16:54:23 -07001899 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001900 mLeftVolume = left;
1901 mRightVolume = right;
Glenn Kasten2799d742013-05-30 14:33:29 -07001902 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001903 mTrack->setVolume(left, right);
1904 }
1905}
1906
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001907status_t MediaPlayerService::AudioOutput::setPlaybackRate(const AudioPlaybackRate &rate)
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001908{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001909 ALOGV("setPlaybackRate(%f %f %d %d)",
1910 rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Andy Hungd1c74342015-07-07 16:54:23 -07001911 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001912 if (mTrack == 0) {
1913 // remember rate so that we can set it when the track is opened
1914 mPlaybackRate = rate;
1915 return OK;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001916 }
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001917 status_t res = mTrack->setPlaybackRate(rate);
1918 if (res != NO_ERROR) {
1919 return res;
1920 }
1921 // rate.mSpeed is always greater than 0 if setPlaybackRate succeeded
1922 CHECK_GT(rate.mSpeed, 0.f);
1923 mPlaybackRate = rate;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001924 if (mSampleRateHz != 0) {
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001925 mMsecsPerFrame = 1E3f / (rate.mSpeed * mSampleRateHz);
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001926 }
1927 return res;
1928}
1929
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001930status_t MediaPlayerService::AudioOutput::getPlaybackRate(AudioPlaybackRate *rate)
1931{
1932 ALOGV("setPlaybackRate");
Andy Hungd1c74342015-07-07 16:54:23 -07001933 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001934 if (mTrack == 0) {
1935 return NO_INIT;
1936 }
1937 *rate = mTrack->getPlaybackRate();
1938 return NO_ERROR;
1939}
1940
Eric Laurent2beeb502010-07-16 07:43:46 -07001941status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
1942{
Steve Block3856b092011-10-20 11:56:00 +01001943 ALOGV("setAuxEffectSendLevel(%f)", level);
Andy Hungd1c74342015-07-07 16:54:23 -07001944 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07001945 mSendLevel = level;
Glenn Kasten2799d742013-05-30 14:33:29 -07001946 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07001947 return mTrack->setAuxEffectSendLevel(level);
1948 }
1949 return NO_ERROR;
1950}
1951
1952status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
1953{
Steve Block3856b092011-10-20 11:56:00 +01001954 ALOGV("attachAuxEffect(%d)", effectId);
Andy Hungd1c74342015-07-07 16:54:23 -07001955 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07001956 mAuxEffectId = effectId;
Glenn Kasten2799d742013-05-30 14:33:29 -07001957 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07001958 return mTrack->attachAuxEffect(effectId);
1959 }
1960 return NO_ERROR;
1961}
1962
Andreas Huber20111aa2009-07-14 16:56:47 -07001963// static
1964void MediaPlayerService::AudioOutput::CallbackWrapper(
Glenn Kastend217a8c2011-06-01 15:20:35 -07001965 int event, void *cookie, void *info) {
Steve Block3856b092011-10-20 11:56:00 +01001966 //ALOGV("callbackwrapper");
Marco Nelissen6b74d672012-02-28 16:07:44 -08001967 CallbackData *data = (CallbackData*)cookie;
Andy Hungd1c74342015-07-07 16:54:23 -07001968 // lock to ensure we aren't caught in the middle of a track switch.
Marco Nelissen6b74d672012-02-28 16:07:44 -08001969 data->lock();
1970 AudioOutput *me = data->getOutput();
Andreas Huber20111aa2009-07-14 16:56:47 -07001971 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001972 if (me == NULL) {
1973 // no output set, likely because the track was scheduled to be reused
1974 // by another player, but the format turned out to be incompatible.
1975 data->unlock();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001976 if (buffer != NULL) {
1977 buffer->size = 0;
1978 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001979 return;
1980 }
Andreas Huber20111aa2009-07-14 16:56:47 -07001981
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001982 switch(event) {
1983 case AudioTrack::EVENT_MORE_DATA: {
1984 size_t actualSize = (*me->mCallback)(
1985 me, buffer->raw, buffer->size, me->mCallbackCookie,
1986 CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08001987
Andy Hung719b46b2015-05-31 22:18:25 -07001988 // Log when no data is returned from the callback.
1989 // (1) We may have no data (especially with network streaming sources).
1990 // (2) We may have reached the EOS and the audio track is not stopped yet.
1991 // Note that AwesomePlayer/AudioPlayer will only return zero size when it reaches the EOS.
1992 // NuPlayerRenderer will return zero when it doesn't have data (it doesn't block to fill).
1993 //
1994 // This is a benign busy-wait, with the next data request generated 10 ms or more later;
1995 // nevertheless for power reasons, we don't want to see too many of these.
Andreas Huber2e8ffaf2010-02-18 16:45:13 -08001996
Andy Hung719b46b2015-05-31 22:18:25 -07001997 ALOGV_IF(actualSize == 0 && buffer->size > 0, "callbackwrapper: empty buffer returned");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001998
Andy Hung719b46b2015-05-31 22:18:25 -07001999 me->mBytesWritten += actualSize; // benign race with reader.
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002000 buffer->size = actualSize;
2001 } break;
2002
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002003 case AudioTrack::EVENT_STREAM_END:
Andy Hung719b46b2015-05-31 22:18:25 -07002004 // currently only occurs for offloaded callbacks
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002005 ALOGV("callbackwrapper: deliver EVENT_STREAM_END");
2006 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2007 me->mCallbackCookie, CB_EVENT_STREAM_END);
2008 break;
2009
2010 case AudioTrack::EVENT_NEW_IAUDIOTRACK :
2011 ALOGV("callbackwrapper: deliver EVENT_TEAR_DOWN");
2012 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2013 me->mCallbackCookie, CB_EVENT_TEAR_DOWN);
2014 break;
2015
Glenn Kasten421743b2015-06-01 08:18:08 -07002016 case AudioTrack::EVENT_UNDERRUN:
Andy Hung719b46b2015-05-31 22:18:25 -07002017 // This occurs when there is no data available, typically
Glenn Kasten421743b2015-06-01 08:18:08 -07002018 // when there is a failure to supply data to the AudioTrack. It can also
2019 // occur in non-offloaded mode when the audio device comes out of standby.
2020 //
Andy Hung719b46b2015-05-31 22:18:25 -07002021 // If an AudioTrack underruns it outputs silence. Since this happens suddenly
2022 // it may sound like an audible pop or glitch.
2023 //
2024 // The underrun event is sent once per track underrun; the condition is reset
2025 // when more data is sent to the AudioTrack.
Glenn Kasten421743b2015-06-01 08:18:08 -07002026 ALOGI("callbackwrapper: EVENT_UNDERRUN (discarded)");
2027 break;
2028
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002029 default:
2030 ALOGE("received unknown event type: %d inside CallbackWrapper !", event);
Andreas Huber51c1e0e2011-04-04 11:43:40 -07002031 }
2032
Marco Nelissen6b74d672012-02-28 16:07:44 -08002033 data->unlock();
Andreas Huber20111aa2009-07-14 16:56:47 -07002034}
2035
Marco Nelissen4110c102012-03-29 09:31:28 -07002036int MediaPlayerService::AudioOutput::getSessionId() const
Eric Laurent8c563ed2010-10-07 18:23:03 -07002037{
Andy Hungd1c74342015-07-07 16:54:23 -07002038 Mutex::Autolock lock(mLock);
Eric Laurent8c563ed2010-10-07 18:23:03 -07002039 return mSessionId;
2040}
2041
Eric Laurent6f59db12013-07-26 17:16:50 -07002042uint32_t MediaPlayerService::AudioOutput::getSampleRate() const
2043{
Andy Hungd1c74342015-07-07 16:54:23 -07002044 Mutex::Autolock lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -07002045 if (mTrack == 0) return 0;
2046 return mTrack->getSampleRate();
2047}
2048
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002049////////////////////////////////////////////////////////////////////////////////
2050
2051struct CallbackThread : public Thread {
2052 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
2053 MediaPlayerBase::AudioSink::AudioCallback cb,
2054 void *cookie);
2055
2056protected:
2057 virtual ~CallbackThread();
2058
2059 virtual bool threadLoop();
2060
2061private:
2062 wp<MediaPlayerBase::AudioSink> mSink;
2063 MediaPlayerBase::AudioSink::AudioCallback mCallback;
2064 void *mCookie;
2065 void *mBuffer;
2066 size_t mBufferSize;
2067
2068 CallbackThread(const CallbackThread &);
2069 CallbackThread &operator=(const CallbackThread &);
2070};
2071
2072CallbackThread::CallbackThread(
2073 const wp<MediaPlayerBase::AudioSink> &sink,
2074 MediaPlayerBase::AudioSink::AudioCallback cb,
2075 void *cookie)
2076 : mSink(sink),
2077 mCallback(cb),
2078 mCookie(cookie),
2079 mBuffer(NULL),
2080 mBufferSize(0) {
2081}
2082
2083CallbackThread::~CallbackThread() {
2084 if (mBuffer) {
2085 free(mBuffer);
2086 mBuffer = NULL;
2087 }
2088}
2089
2090bool CallbackThread::threadLoop() {
2091 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
2092 if (sink == NULL) {
2093 return false;
2094 }
2095
2096 if (mBuffer == NULL) {
2097 mBufferSize = sink->bufferSize();
2098 mBuffer = malloc(mBufferSize);
2099 }
2100
2101 size_t actualSize =
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002102 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie,
2103 MediaPlayerBase::AudioSink::CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002104
2105 if (actualSize > 0) {
2106 sink->write(mBuffer, actualSize);
Andy Hunga31335a2014-08-20 17:37:59 -07002107 // Could return false on sink->write() error or short count.
2108 // Not necessarily appropriate but would work for AudioCache behavior.
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002109 }
2110
2111 return true;
2112}
2113
2114////////////////////////////////////////////////////////////////////////////////
2115
Gloria Wang7cf180c2011-02-19 18:37:57 -08002116void MediaPlayerService::addBatteryData(uint32_t params)
2117{
2118 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002119
2120 int32_t time = systemTime() / 1000000L;
2121
2122 // change audio output devices. This notification comes from AudioFlinger
2123 if ((params & kBatteryDataSpeakerOn)
2124 || (params & kBatteryDataOtherAudioDeviceOn)) {
2125
2126 int deviceOn[NUM_AUDIO_DEVICES];
2127 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2128 deviceOn[i] = 0;
2129 }
2130
2131 if ((params & kBatteryDataSpeakerOn)
2132 && (params & kBatteryDataOtherAudioDeviceOn)) {
2133 deviceOn[SPEAKER_AND_OTHER] = 1;
2134 } else if (params & kBatteryDataSpeakerOn) {
2135 deviceOn[SPEAKER] = 1;
2136 } else {
2137 deviceOn[OTHER_AUDIO_DEVICE] = 1;
2138 }
2139
2140 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2141 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
2142
2143 if (mBatteryAudio.refCount > 0) { // if playing audio
2144 if (!deviceOn[i]) {
2145 mBatteryAudio.lastTime[i] += time;
2146 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2147 mBatteryAudio.lastTime[i] = 0;
2148 } else {
2149 mBatteryAudio.lastTime[i] = 0 - time;
2150 }
2151 }
2152
2153 mBatteryAudio.deviceOn[i] = deviceOn[i];
2154 }
2155 }
2156 return;
2157 }
2158
Marco Nelissenb7848f12014-12-04 08:57:56 -08002159 // an audio stream is started
Gloria Wang9ee159b2011-02-24 14:51:45 -08002160 if (params & kBatteryDataAudioFlingerStart) {
2161 // record the start time only if currently no other audio
2162 // is being played
2163 if (mBatteryAudio.refCount == 0) {
2164 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2165 if (mBatteryAudio.deviceOn[i]) {
2166 mBatteryAudio.lastTime[i] -= time;
2167 }
2168 }
2169 }
2170
2171 mBatteryAudio.refCount ++;
2172 return;
2173
2174 } else if (params & kBatteryDataAudioFlingerStop) {
2175 if (mBatteryAudio.refCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002176 ALOGW("Battery track warning: refCount is <= 0");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002177 return;
2178 }
2179
2180 // record the stop time only if currently this is the only
2181 // audio being played
2182 if (mBatteryAudio.refCount == 1) {
2183 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2184 if (mBatteryAudio.deviceOn[i]) {
2185 mBatteryAudio.lastTime[i] += time;
2186 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2187 mBatteryAudio.lastTime[i] = 0;
2188 }
2189 }
2190 }
2191
2192 mBatteryAudio.refCount --;
2193 return;
2194 }
2195
Gloria Wang7cf180c2011-02-19 18:37:57 -08002196 int uid = IPCThreadState::self()->getCallingUid();
2197 if (uid == AID_MEDIA) {
2198 return;
2199 }
2200 int index = mBatteryData.indexOfKey(uid);
Gloria Wang7cf180c2011-02-19 18:37:57 -08002201
2202 if (index < 0) { // create a new entry for this UID
2203 BatteryUsageInfo info;
2204 info.audioTotalTime = 0;
2205 info.videoTotalTime = 0;
2206 info.audioLastTime = 0;
2207 info.videoLastTime = 0;
2208 info.refCount = 0;
2209
Gloria Wang9ee159b2011-02-24 14:51:45 -08002210 if (mBatteryData.add(uid, info) == NO_MEMORY) {
Steve Block29357bc2012-01-06 19:20:56 +00002211 ALOGE("Battery track error: no memory for new app");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002212 return;
2213 }
Gloria Wang7cf180c2011-02-19 18:37:57 -08002214 }
2215
2216 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
2217
2218 if (params & kBatteryDataCodecStarted) {
2219 if (params & kBatteryDataTrackAudio) {
2220 info.audioLastTime -= time;
2221 info.refCount ++;
2222 }
2223 if (params & kBatteryDataTrackVideo) {
2224 info.videoLastTime -= time;
2225 info.refCount ++;
2226 }
2227 } else {
2228 if (info.refCount == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002229 ALOGW("Battery track warning: refCount is already 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002230 return;
2231 } else if (info.refCount < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00002232 ALOGE("Battery track error: refCount < 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002233 mBatteryData.removeItem(uid);
2234 return;
2235 }
2236
2237 if (params & kBatteryDataTrackAudio) {
2238 info.audioLastTime += time;
2239 info.refCount --;
2240 }
2241 if (params & kBatteryDataTrackVideo) {
2242 info.videoLastTime += time;
2243 info.refCount --;
2244 }
2245
2246 // no stream is being played by this UID
2247 if (info.refCount == 0) {
2248 info.audioTotalTime += info.audioLastTime;
2249 info.audioLastTime = 0;
2250 info.videoTotalTime += info.videoLastTime;
2251 info.videoLastTime = 0;
2252 }
2253 }
2254}
2255
2256status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
2257 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002258
2259 // audio output devices usage
2260 int32_t time = systemTime() / 1000000L; //in ms
2261 int32_t totalTime;
2262
2263 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2264 totalTime = mBatteryAudio.totalTime[i];
2265
2266 if (mBatteryAudio.deviceOn[i]
2267 && (mBatteryAudio.lastTime[i] != 0)) {
2268 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
2269 totalTime += tmpTime;
2270 }
2271
2272 reply->writeInt32(totalTime);
2273 // reset the total time
2274 mBatteryAudio.totalTime[i] = 0;
2275 }
2276
2277 // codec usage
Gloria Wang7cf180c2011-02-19 18:37:57 -08002278 BatteryUsageInfo info;
2279 int size = mBatteryData.size();
2280
2281 reply->writeInt32(size);
2282 int i = 0;
2283
2284 while (i < size) {
2285 info = mBatteryData.valueAt(i);
2286
2287 reply->writeInt32(mBatteryData.keyAt(i)); //UID
2288 reply->writeInt32(info.audioTotalTime);
2289 reply->writeInt32(info.videoTotalTime);
2290
2291 info.audioTotalTime = 0;
2292 info.videoTotalTime = 0;
2293
2294 // remove the UID entry where no stream is being played
2295 if (info.refCount <= 0) {
2296 mBatteryData.removeItemsAt(i);
2297 size --;
2298 i --;
2299 }
2300 i++;
2301 }
2302 return NO_ERROR;
2303}
nikoa64c8c72009-07-20 15:07:26 -07002304} // namespace android