blob: d49ba93ce76cf9a13e486b993848bb48b2c0f46d [file] [log] [blame]
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001/*
2**
3** Copyright 2008, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18// Proxy for media player implementations
19
20//#define LOG_NDEBUG 0
21#define LOG_TAG "MediaPlayerService"
22#include <utils/Log.h>
23
24#include <sys/types.h>
25#include <sys/stat.h>
Gloria Wang7cf180c2011-02-19 18:37:57 -080026#include <sys/time.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080027#include <dirent.h>
28#include <unistd.h>
29
30#include <string.h>
Mathias Agopian6f74b0c2009-06-03 17:32:49 -070031
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080032#include <cutils/atomic.h>
Nicolas Catania14d27472009-07-13 14:37:49 -070033#include <cutils/properties.h> // for property_get
Mathias Agopian6f74b0c2009-06-03 17:32:49 -070034
35#include <utils/misc.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080036
Mathias Agopian75624082009-05-19 19:08:10 -070037#include <binder/IPCThreadState.h>
38#include <binder/IServiceManager.h>
39#include <binder/MemoryHeapBase.h>
40#include <binder/MemoryBase.h>
Mathias Agopianb1e7cd12013-02-14 17:11:27 -080041#include <gui/Surface.h>
Nicolas Catania1d187f12009-05-12 23:25:55 -070042#include <utils/Errors.h> // for status_t
43#include <utils/String8.h>
Marco Nelissen10dbb8e2009-09-20 10:42:13 -070044#include <utils/SystemClock.h>
Lajos Molnar06ad1522014-08-28 07:27:44 -070045#include <utils/Timers.h>
Nicolas Catania1d187f12009-05-12 23:25:55 -070046#include <utils/Vector.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080047
Eric Laurent43562692015-07-15 16:49:07 -070048#include <media/AudioPolicyHelper.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080049#include <media/IMediaHTTPService.h>
Jeff Brown2013a542012-09-04 21:38:42 -070050#include <media/IRemoteDisplay.h>
51#include <media/IRemoteDisplayClient.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080052#include <media/MediaPlayerInterface.h>
53#include <media/mediarecorder.h>
54#include <media/MediaMetadataRetrieverInterface.h>
nikoa64c8c72009-07-20 15:07:26 -070055#include <media/Metadata.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080056#include <media/AudioTrack.h>
James Dong8635b7b2011-03-14 17:01:38 -070057#include <media/MemoryLeakTrackUtil.h>
Lajos Molnar1381d4b2014-08-07 15:18:35 -070058#include <media/stagefright/MediaCodecList.h>
Eric Laurent9cb839a2011-09-27 09:48:56 -070059#include <media/stagefright/MediaErrors.h>
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +010060#include <media/stagefright/AudioPlayer.h>
61#include <media/stagefright/foundation/ADebug.h>
Marco Nelissenf09611f2015-02-13 14:12:42 -080062#include <media/stagefright/foundation/ALooperRoster.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070063#include <mediautils/BatteryNotifier.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080064
Dima Zavin64760242011-05-11 14:15:23 -070065#include <system/audio.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070066
Gloria Wang7cf180c2011-02-19 18:37:57 -080067#include <private/android_filesystem_config.h>
68
James Dong559bf282012-03-28 10:29:14 -070069#include "ActivityManager.h"
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080070#include "MediaRecorderClient.h"
71#include "MediaPlayerService.h"
72#include "MetadataRetrieverClient.h"
John Grossman44a7e422012-06-21 17:29:24 -070073#include "MediaPlayerFactory.h"
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080074
Nicolas Catania14d27472009-07-13 14:37:49 -070075#include "TestPlayerStub.h"
Andreas Huber20111aa2009-07-14 16:56:47 -070076#include "StagefrightPlayer.h"
Andreas Huberf9334412010-12-15 15:17:42 -080077#include "nuplayer/NuPlayerDriver.h"
Andreas Huber20111aa2009-07-14 16:56:47 -070078
Andreas Huber20111aa2009-07-14 16:56:47 -070079#include <OMX.h>
Nicolas Catania14d27472009-07-13 14:37:49 -070080
Andreas Hubered3e3e02012-03-26 11:13:27 -070081#include "Crypto.h"
Jeff Tinkercc82dc62013-02-08 10:18:35 -080082#include "Drm.h"
Andreas Huber59451f82012-09-18 10:36:32 -070083#include "HDCP.h"
Andreas Huberb7319a72013-05-29 14:20:52 -070084#include "HTTPBase.h"
Andreas Huber35213f12012-08-29 11:41:50 -070085#include "RemoteDisplay.h"
Andreas Hubered3e3e02012-03-26 11:13:27 -070086
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070087namespace {
nikoa64c8c72009-07-20 15:07:26 -070088using android::media::Metadata;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070089using android::status_t;
90using android::OK;
91using android::BAD_VALUE;
92using android::NOT_ENOUGH_DATA;
93using android::Parcel;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070094
95// Max number of entries in the filter.
96const int kMaxFilterSize = 64; // I pulled that out of thin air.
97
nikoa64c8c72009-07-20 15:07:26 -070098// FIXME: Move all the metadata related function in the Metadata.cpp
nikod608a812009-07-16 16:39:53 -070099
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700100
101// Unmarshall a filter from a Parcel.
102// Filter format in a parcel:
103//
104// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
105// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
106// | number of entries (n) |
107// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
108// | metadata type 1 |
109// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
110// | metadata type 2 |
111// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
112// ....
113// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
114// | metadata type n |
115// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
116//
117// @param p Parcel that should start with a filter.
118// @param[out] filter On exit contains the list of metadata type to be
119// filtered.
120// @param[out] status On exit contains the status code to be returned.
121// @return true if the parcel starts with a valid filter.
122bool unmarshallFilter(const Parcel& p,
nikoa64c8c72009-07-20 15:07:26 -0700123 Metadata::Filter *filter,
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700124 status_t *status)
125{
Nicolas Catania48290382009-07-10 13:53:06 -0700126 int32_t val;
127 if (p.readInt32(&val) != OK)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700128 {
Steve Block29357bc2012-01-06 19:20:56 +0000129 ALOGE("Failed to read filter's length");
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700130 *status = NOT_ENOUGH_DATA;
131 return false;
132 }
133
Nicolas Catania48290382009-07-10 13:53:06 -0700134 if( val > kMaxFilterSize || val < 0)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700135 {
Steve Block29357bc2012-01-06 19:20:56 +0000136 ALOGE("Invalid filter len %d", val);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700137 *status = BAD_VALUE;
138 return false;
139 }
140
Nicolas Catania48290382009-07-10 13:53:06 -0700141 const size_t num = val;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700142
143 filter->clear();
Nicolas Catania48290382009-07-10 13:53:06 -0700144 filter->setCapacity(num);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700145
nikoa64c8c72009-07-20 15:07:26 -0700146 size_t size = num * sizeof(Metadata::Type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700147
Nicolas Catania48290382009-07-10 13:53:06 -0700148
149 if (p.dataAvail() < size)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700150 {
Steve Block29357bc2012-01-06 19:20:56 +0000151 ALOGE("Filter too short expected %d but got %d", size, p.dataAvail());
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700152 *status = NOT_ENOUGH_DATA;
153 return false;
154 }
155
nikoa64c8c72009-07-20 15:07:26 -0700156 const Metadata::Type *data =
157 static_cast<const Metadata::Type*>(p.readInplace(size));
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700158
Nicolas Catania48290382009-07-10 13:53:06 -0700159 if (NULL == data)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700160 {
Steve Block29357bc2012-01-06 19:20:56 +0000161 ALOGE("Filter had no data");
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700162 *status = BAD_VALUE;
163 return false;
164 }
165
166 // TODO: The stl impl of vector would be more efficient here
167 // because it degenerates into a memcpy on pod types. Try to
168 // replace later or use stl::set.
Nicolas Catania48290382009-07-10 13:53:06 -0700169 for (size_t i = 0; i < num; ++i)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700170 {
Nicolas Catania48290382009-07-10 13:53:06 -0700171 filter->add(*data);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700172 ++data;
173 }
174 *status = OK;
175 return true;
176}
177
Nicolas Catania48290382009-07-10 13:53:06 -0700178// @param filter Of metadata type.
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700179// @param val To be searched.
180// @return true if a match was found.
nikoa64c8c72009-07-20 15:07:26 -0700181bool findMetadata(const Metadata::Filter& filter, const int32_t val)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700182{
183 // Deal with empty and ANY right away
184 if (filter.isEmpty()) return false;
nikoa64c8c72009-07-20 15:07:26 -0700185 if (filter[0] == Metadata::kAny) return true;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700186
Nicolas Catania48290382009-07-10 13:53:06 -0700187 return filter.indexOf(val) >= 0;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700188}
189
190} // anonymous namespace
191
192
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700193namespace {
194using android::Parcel;
195using android::String16;
196
197// marshalling tag indicating flattened utf16 tags
198// keep in sync with frameworks/base/media/java/android/media/AudioAttributes.java
199const int32_t kAudioAttributesMarshallTagFlattenTags = 1;
200
201// Audio attributes format in a parcel:
202//
203// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
204// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
205// | usage |
206// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
207// | content_type |
208// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Hyejin Kim4f418f92014-09-05 15:50:03 +0900209// | source |
210// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700211// | flags |
212// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
213// | kAudioAttributesMarshallTagFlattenTags | // ignore tags if not found
214// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
215// | flattened tags in UTF16 |
216// | ... |
217// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
218//
219// @param p Parcel that contains audio attributes.
220// @param[out] attributes On exit points to an initialized audio_attributes_t structure
221// @param[out] status On exit contains the status code to be returned.
222void unmarshallAudioAttributes(const Parcel& parcel, audio_attributes_t *attributes)
223{
224 attributes->usage = (audio_usage_t) parcel.readInt32();
225 attributes->content_type = (audio_content_type_t) parcel.readInt32();
Hyejin Kim4f418f92014-09-05 15:50:03 +0900226 attributes->source = (audio_source_t) parcel.readInt32();
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700227 attributes->flags = (audio_flags_mask_t) parcel.readInt32();
228 const bool hasFlattenedTag = (parcel.readInt32() == kAudioAttributesMarshallTagFlattenTags);
229 if (hasFlattenedTag) {
230 // the tags are UTF16, convert to UTF8
231 String16 tags = parcel.readString16();
232 ssize_t realTagSize = utf16_to_utf8_length(tags.string(), tags.size());
233 if (realTagSize <= 0) {
234 strcpy(attributes->tags, "");
235 } else {
236 // copy the flattened string into the attributes as the destination for the conversion:
237 // copying array size -1, array for tags was calloc'd, no need to NULL-terminate it
238 size_t tagSize = realTagSize > AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 ?
239 AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 : realTagSize;
240 utf16_to_utf8(tags.string(), tagSize, attributes->tags);
241 }
242 } else {
243 ALOGE("unmarshallAudioAttributes() received unflattened tags, ignoring tag values");
244 strcpy(attributes->tags, "");
245 }
246}
247} // anonymous namespace
248
249
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800250namespace android {
251
Marco Nelissenf09611f2015-02-13 14:12:42 -0800252extern ALooperRoster gLooperRoster;
253
254
Dave Burked681bbb2011-08-30 14:39:17 +0100255static bool checkPermission(const char* permissionString) {
256#ifndef HAVE_ANDROID_OS
257 return true;
258#endif
259 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
260 bool ok = checkCallingPermission(String16(permissionString));
Steve Block29357bc2012-01-06 19:20:56 +0000261 if (!ok) ALOGE("Request requires %s", permissionString);
Dave Burked681bbb2011-08-30 14:39:17 +0100262 return ok;
263}
264
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800265// 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 -0800266/* static */ int MediaPlayerService::AudioOutput::mMinBufferCount = 4;
267/* static */ bool MediaPlayerService::AudioOutput::mIsOnEmulator = false;
268
269void MediaPlayerService::instantiate() {
270 defaultServiceManager()->addService(
271 String16("media.player"), new MediaPlayerService());
272}
273
274MediaPlayerService::MediaPlayerService()
275{
Steve Block3856b092011-10-20 11:56:00 +0100276 ALOGV("MediaPlayerService created");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800277 mNextConnId = 1;
Gloria Wang9ee159b2011-02-24 14:51:45 -0800278
279 mBatteryAudio.refCount = 0;
280 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
281 mBatteryAudio.deviceOn[i] = 0;
282 mBatteryAudio.lastTime[i] = 0;
283 mBatteryAudio.totalTime[i] = 0;
284 }
285 // speaker is on by default
286 mBatteryAudio.deviceOn[SPEAKER] = 1;
John Grossman44a7e422012-06-21 17:29:24 -0700287
Chong Zhang0b30fd42014-07-23 14:46:05 -0700288 // reset battery stats
289 // if the mediaserver has crashed, battery stats could be left
290 // in bad state, reset the state upon service start.
Ruben Brunk99e69712015-05-26 17:25:07 -0700291 BatteryNotifier& notifier(BatteryNotifier::getInstance());
292 notifier.noteResetVideo();
293 notifier.noteResetAudio();
Chong Zhang0b30fd42014-07-23 14:46:05 -0700294
John Grossman44a7e422012-06-21 17:29:24 -0700295 MediaPlayerFactory::registerBuiltinFactories();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800296}
297
298MediaPlayerService::~MediaPlayerService()
299{
Steve Block3856b092011-10-20 11:56:00 +0100300 ALOGV("MediaPlayerService destroyed");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800301}
302
Svet Ganovbe71aa22015-04-28 12:06:02 -0700303sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(const String16 &opPackageName)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800304{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800305 pid_t pid = IPCThreadState::self()->getCallingPid();
Svet Ganovbe71aa22015-04-28 12:06:02 -0700306 sp<MediaRecorderClient> recorder = new MediaRecorderClient(this, pid, opPackageName);
Gloria Wangdac6a312009-10-29 15:46:37 -0700307 wp<MediaRecorderClient> w = recorder;
308 Mutex::Autolock lock(mLock);
309 mMediaRecorderClients.add(w);
Steve Block3856b092011-10-20 11:56:00 +0100310 ALOGV("Create new media recorder client from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800311 return recorder;
312}
313
Gloria Wangdac6a312009-10-29 15:46:37 -0700314void MediaPlayerService::removeMediaRecorderClient(wp<MediaRecorderClient> client)
315{
316 Mutex::Autolock lock(mLock);
317 mMediaRecorderClients.remove(client);
Steve Block3856b092011-10-20 11:56:00 +0100318 ALOGV("Delete media recorder client");
Gloria Wangdac6a312009-10-29 15:46:37 -0700319}
320
Glenn Kastenf37971f2012-02-03 11:06:53 -0800321sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800322{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800323 pid_t pid = IPCThreadState::self()->getCallingPid();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800324 sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
Steve Block3856b092011-10-20 11:56:00 +0100325 ALOGV("Create new media retriever from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800326 return retriever;
327}
328
Glenn Kastenf37971f2012-02-03 11:06:53 -0800329sp<IMediaPlayer> MediaPlayerService::create(const sp<IMediaPlayerClient>& client,
Dave Burked681bbb2011-08-30 14:39:17 +0100330 int audioSessionId)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800331{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800332 pid_t pid = IPCThreadState::self()->getCallingPid();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800333 int32_t connId = android_atomic_inc(&mNextConnId);
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700334
335 sp<Client> c = new Client(
336 this, pid, connId, client, audioSessionId,
337 IPCThreadState::self()->getCallingUid());
338
Steve Block3856b092011-10-20 11:56:00 +0100339 ALOGV("Create new client(%d) from pid %d, uid %d, ", connId, pid,
Dave Burked681bbb2011-08-30 14:39:17 +0100340 IPCThreadState::self()->getCallingUid());
341
342 wp<Client> w = c;
343 {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800344 Mutex::Autolock lock(mLock);
345 mClients.add(w);
346 }
Andreas Hubere2b10282010-11-23 11:41:34 -0800347 return c;
348}
349
Lajos Molnar1381d4b2014-08-07 15:18:35 -0700350sp<IMediaCodecList> MediaPlayerService::getCodecList() const {
351 return MediaCodecList::getLocalInstance();
352}
353
Andreas Huber318ad9c2009-10-15 13:46:54 -0700354sp<IOMX> MediaPlayerService::getOMX() {
355 Mutex::Autolock autoLock(mLock);
356
357 if (mOMX.get() == NULL) {
358 mOMX = new OMX;
359 }
360
361 return mOMX;
Andreas Huber20111aa2009-07-14 16:56:47 -0700362}
363
Andreas Hubered3e3e02012-03-26 11:13:27 -0700364sp<ICrypto> MediaPlayerService::makeCrypto() {
Andreas Huber1bd139a2012-04-03 14:19:20 -0700365 return new Crypto;
Andreas Hubered3e3e02012-03-26 11:13:27 -0700366}
367
Jeff Tinkercc82dc62013-02-08 10:18:35 -0800368sp<IDrm> MediaPlayerService::makeDrm() {
369 return new Drm;
370}
371
Andreas Huber279dcd82013-01-30 10:41:25 -0800372sp<IHDCP> MediaPlayerService::makeHDCP(bool createEncryptionModule) {
373 return new HDCP(createEncryptionModule);
Andreas Huber59451f82012-09-18 10:36:32 -0700374}
375
Jeff Brown2013a542012-09-04 21:38:42 -0700376sp<IRemoteDisplay> MediaPlayerService::listenForRemoteDisplay(
Svet Ganovbe71aa22015-04-28 12:06:02 -0700377 const String16 &opPackageName,
Jeff Brown2013a542012-09-04 21:38:42 -0700378 const sp<IRemoteDisplayClient>& client, const String8& iface) {
Jeff Brownaba33d52012-09-07 17:38:58 -0700379 if (!checkPermission("android.permission.CONTROL_WIFI_DISPLAY")) {
380 return NULL;
381 }
382
Svet Ganovbe71aa22015-04-28 12:06:02 -0700383 return new RemoteDisplay(opPackageName, client, iface.string());
Jeff Brown2013a542012-09-04 21:38:42 -0700384}
385
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800386status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
387{
388 const size_t SIZE = 256;
389 char buffer[SIZE];
390 String8 result;
391
392 result.append(" AudioOutput\n");
393 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n",
394 mStreamType, mLeftVolume, mRightVolume);
395 result.append(buffer);
396 snprintf(buffer, 255, " msec per frame(%f), latency (%d)\n",
Eric Laurentdb354e52012-03-05 17:27:11 -0800397 mMsecsPerFrame, (mTrack != 0) ? mTrack->latency() : -1);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800398 result.append(buffer);
Eric Laurent2beeb502010-07-16 07:43:46 -0700399 snprintf(buffer, 255, " aux effect id(%d), send level (%f)\n",
400 mAuxEffectId, mSendLevel);
401 result.append(buffer);
402
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800403 ::write(fd, result.string(), result.size());
404 if (mTrack != 0) {
405 mTrack->dump(fd, args);
406 }
407 return NO_ERROR;
408}
409
Lajos Molnar6d339f12015-04-17 16:15:53 -0700410status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800411{
412 const size_t SIZE = 256;
413 char buffer[SIZE];
414 String8 result;
415 result.append(" Client\n");
416 snprintf(buffer, 255, " pid(%d), connId(%d), status(%d), looping(%s)\n",
417 mPid, mConnId, mStatus, mLoop?"true": "false");
418 result.append(buffer);
419 write(fd, result.string(), result.size());
Andreas Hubera0b1d4b2011-06-07 15:52:25 -0700420 if (mPlayer != NULL) {
421 mPlayer->dump(fd, args);
422 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800423 if (mAudioOutput != 0) {
424 mAudioOutput->dump(fd, args);
425 }
426 write(fd, "\n", 1);
427 return NO_ERROR;
428}
429
Marco Nelissenf09611f2015-02-13 14:12:42 -0800430/**
431 * The only arguments this understands right now are -c, -von and -voff,
432 * which are parsed by ALooperRoster::dump()
433 */
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800434status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
435{
436 const size_t SIZE = 256;
437 char buffer[SIZE];
438 String8 result;
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530439 SortedVector< sp<Client> > clients; //to serialise the mutex unlock & client destruction.
440 SortedVector< sp<MediaRecorderClient> > mediaRecorderClients;
441
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800442 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
443 snprintf(buffer, SIZE, "Permission Denial: "
444 "can't dump MediaPlayerService from pid=%d, uid=%d\n",
445 IPCThreadState::self()->getCallingPid(),
446 IPCThreadState::self()->getCallingUid());
447 result.append(buffer);
448 } else {
449 Mutex::Autolock lock(mLock);
450 for (int i = 0, n = mClients.size(); i < n; ++i) {
451 sp<Client> c = mClients[i].promote();
452 if (c != 0) c->dump(fd, args);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530453 clients.add(c);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800454 }
James Dongb9141222010-07-08 11:16:11 -0700455 if (mMediaRecorderClients.size() == 0) {
456 result.append(" No media recorder client\n\n");
457 } else {
458 for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
459 sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
James Donge579e282011-10-18 22:29:20 -0700460 if (c != 0) {
461 snprintf(buffer, 255, " MediaRecorderClient pid(%d)\n", c->mPid);
462 result.append(buffer);
463 write(fd, result.string(), result.size());
464 result = "\n";
465 c->dump(fd, args);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530466 mediaRecorderClients.add(c);
James Donge579e282011-10-18 22:29:20 -0700467 }
James Dongb9141222010-07-08 11:16:11 -0700468 }
Gloria Wangdac6a312009-10-29 15:46:37 -0700469 }
470
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800471 result.append(" Files opened and/or mapped:\n");
Marco Nelissenf09611f2015-02-13 14:12:42 -0800472 snprintf(buffer, SIZE, "/proc/%d/maps", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800473 FILE *f = fopen(buffer, "r");
474 if (f) {
475 while (!feof(f)) {
476 fgets(buffer, SIZE, f);
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700477 if (strstr(buffer, " /storage/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800478 strstr(buffer, " /system/sounds/") ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700479 strstr(buffer, " /data/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800480 strstr(buffer, " /system/media/")) {
481 result.append(" ");
482 result.append(buffer);
483 }
484 }
485 fclose(f);
486 } else {
487 result.append("couldn't open ");
488 result.append(buffer);
489 result.append("\n");
490 }
491
Marco Nelissenf09611f2015-02-13 14:12:42 -0800492 snprintf(buffer, SIZE, "/proc/%d/fd", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800493 DIR *d = opendir(buffer);
494 if (d) {
495 struct dirent *ent;
496 while((ent = readdir(d)) != NULL) {
497 if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
Marco Nelissenf09611f2015-02-13 14:12:42 -0800498 snprintf(buffer, SIZE, "/proc/%d/fd/%s", getpid(), ent->d_name);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800499 struct stat s;
500 if (lstat(buffer, &s) == 0) {
501 if ((s.st_mode & S_IFMT) == S_IFLNK) {
502 char linkto[256];
503 int len = readlink(buffer, linkto, sizeof(linkto));
504 if(len > 0) {
505 if(len > 255) {
506 linkto[252] = '.';
507 linkto[253] = '.';
508 linkto[254] = '.';
509 linkto[255] = 0;
510 } else {
511 linkto[len] = 0;
512 }
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700513 if (strstr(linkto, "/storage/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800514 strstr(linkto, "/system/sounds/") == linkto ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700515 strstr(linkto, "/data/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800516 strstr(linkto, "/system/media/") == linkto) {
517 result.append(" ");
518 result.append(buffer);
519 result.append(" -> ");
520 result.append(linkto);
521 result.append("\n");
522 }
523 }
524 } else {
525 result.append(" unexpected type for ");
526 result.append(buffer);
527 result.append("\n");
528 }
529 }
530 }
531 }
532 closedir(d);
533 } else {
534 result.append("couldn't open ");
535 result.append(buffer);
536 result.append("\n");
537 }
538
Marco Nelissenf09611f2015-02-13 14:12:42 -0800539 gLooperRoster.dump(fd, args);
540
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800541 bool dumpMem = false;
542 for (size_t i = 0; i < args.size(); i++) {
543 if (args[i] == String16("-m")) {
544 dumpMem = true;
545 }
546 }
547 if (dumpMem) {
James Dong8635b7b2011-03-14 17:01:38 -0700548 dumpMemoryAddresses(fd);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800549 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800550 }
551 write(fd, result.string(), result.size());
552 return NO_ERROR;
553}
554
555void MediaPlayerService::removeClient(wp<Client> client)
556{
557 Mutex::Autolock lock(mLock);
558 mClients.remove(client);
559}
560
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700561MediaPlayerService::Client::Client(
562 const sp<MediaPlayerService>& service, pid_t pid,
563 int32_t connId, const sp<IMediaPlayerClient>& client,
564 int audioSessionId, uid_t uid)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800565{
Steve Block3856b092011-10-20 11:56:00 +0100566 ALOGV("Client(%d) constructor", connId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800567 mPid = pid;
568 mConnId = connId;
569 mService = service;
570 mClient = client;
571 mLoop = false;
572 mStatus = NO_INIT;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700573 mAudioSessionId = audioSessionId;
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700574 mUID = uid;
John Grossmanc795b642012-02-22 15:38:35 -0800575 mRetransmitEndpointValid = false;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700576 mAudioAttributes = NULL;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700577
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800578#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000579 ALOGD("create Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800580 mAntagonizer = new Antagonizer(notify, this);
581#endif
582}
583
584MediaPlayerService::Client::~Client()
585{
Steve Block3856b092011-10-20 11:56:00 +0100586 ALOGV("Client(%d) destructor pid = %d", mConnId, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800587 mAudioOutput.clear();
588 wp<Client> client(this);
589 disconnect();
590 mService->removeClient(client);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700591 if (mAudioAttributes != NULL) {
592 free(mAudioAttributes);
593 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800594}
595
596void MediaPlayerService::Client::disconnect()
597{
Steve Block3856b092011-10-20 11:56:00 +0100598 ALOGV("disconnect(%d) from pid %d", mConnId, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800599 // grab local reference and clear main reference to prevent future
600 // access to object
601 sp<MediaPlayerBase> p;
602 {
603 Mutex::Autolock l(mLock);
604 p = mPlayer;
beanzdcfefde2012-11-05 09:51:43 +0800605 mClient.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800606 }
Andreas Huber20111aa2009-07-14 16:56:47 -0700607
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800608 mPlayer.clear();
609
610 // clear the notification to prevent callbacks to dead client
611 // and reset the player. We assume the player will serialize
612 // access to itself if necessary.
613 if (p != 0) {
614 p->setNotifyCallback(0, 0);
615#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000616 ALOGD("kill Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800617 mAntagonizer->kill();
618#endif
619 p->reset();
620 }
621
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700622 disconnectNativeWindow();
623
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800624 IPCThreadState::self()->flushCommands();
625}
626
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800627sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
628{
629 // determine if we have the right player type
630 sp<MediaPlayerBase> p = mPlayer;
631 if ((p != NULL) && (p->playerType() != playerType)) {
Steve Block3856b092011-10-20 11:56:00 +0100632 ALOGV("delete player");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800633 p.clear();
634 }
635 if (p == NULL) {
Ronghua Wu68845c12015-07-21 09:50:48 -0700636 p = MediaPlayerFactory::createPlayer(playerType, this, notify, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800637 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700638
Jason Simmonsdb29e522011-08-12 13:46:55 -0700639 if (p != NULL) {
640 p->setUID(mUID);
641 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700642
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800643 return p;
644}
645
John Grossmanc795b642012-02-22 15:38:35 -0800646sp<MediaPlayerBase> MediaPlayerService::Client::setDataSource_pre(
647 player_type playerType)
648{
649 ALOGV("player type = %d", playerType);
650
651 // create the right type of player
652 sp<MediaPlayerBase> p = createPlayer(playerType);
653 if (p == NULL) {
654 return p;
655 }
656
657 if (!p->hardwareOutput()) {
Marco Nelissend457c972014-02-11 08:47:07 -0800658 mAudioOutput = new AudioOutput(mAudioSessionId, IPCThreadState::self()->getCallingUid(),
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700659 mPid, mAudioAttributes);
John Grossmanc795b642012-02-22 15:38:35 -0800660 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
661 }
662
663 return p;
664}
665
666void MediaPlayerService::Client::setDataSource_post(
667 const sp<MediaPlayerBase>& p,
668 status_t status)
669{
670 ALOGV(" setDataSource");
671 mStatus = status;
672 if (mStatus != OK) {
673 ALOGE(" error: %d", mStatus);
674 return;
675 }
676
677 // Set the re-transmission endpoint if one was chosen.
678 if (mRetransmitEndpointValid) {
679 mStatus = p->setRetransmitEndpoint(&mRetransmitEndpoint);
680 if (mStatus != NO_ERROR) {
681 ALOGE("setRetransmitEndpoint error: %d", mStatus);
682 }
683 }
684
685 if (mStatus == OK) {
686 mPlayer = p;
687 }
688}
689
Andreas Huber2db84552010-01-28 11:19:57 -0800690status_t MediaPlayerService::Client::setDataSource(
Andreas Huber1b86fe02014-01-29 11:13:26 -0800691 const sp<IMediaHTTPService> &httpService,
692 const char *url,
693 const KeyedVector<String8, String8> *headers)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800694{
Steve Block3856b092011-10-20 11:56:00 +0100695 ALOGV("setDataSource(%s)", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800696 if (url == NULL)
697 return UNKNOWN_ERROR;
698
Dave Burked681bbb2011-08-30 14:39:17 +0100699 if ((strncmp(url, "http://", 7) == 0) ||
700 (strncmp(url, "https://", 8) == 0) ||
701 (strncmp(url, "rtsp://", 7) == 0)) {
702 if (!checkPermission("android.permission.INTERNET")) {
703 return PERMISSION_DENIED;
704 }
705 }
706
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800707 if (strncmp(url, "content://", 10) == 0) {
708 // get a filedescriptor for the content Uri and
709 // pass it to the setDataSource(fd) method
710
711 String16 url16(url);
712 int fd = android::openContentProviderFile(url16);
713 if (fd < 0)
714 {
Steve Block29357bc2012-01-06 19:20:56 +0000715 ALOGE("Couldn't open fd for %s", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800716 return UNKNOWN_ERROR;
717 }
718 setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
719 close(fd);
720 return mStatus;
721 } else {
John Grossman44a7e422012-06-21 17:29:24 -0700722 player_type playerType = MediaPlayerFactory::getPlayerType(this, url);
John Grossmanc795b642012-02-22 15:38:35 -0800723 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
724 if (p == NULL) {
725 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800726 }
727
Andreas Huber1b86fe02014-01-29 11:13:26 -0800728 setDataSource_post(p, p->setDataSource(httpService, url, headers));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800729 return mStatus;
730 }
731}
732
733status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
734{
Steve Block3856b092011-10-20 11:56:00 +0100735 ALOGV("setDataSource fd=%d, offset=%lld, length=%lld", fd, offset, length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800736 struct stat sb;
737 int ret = fstat(fd, &sb);
738 if (ret != 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000739 ALOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800740 return UNKNOWN_ERROR;
741 }
742
Ying Wang5fde15d2015-04-20 22:13:22 -0700743 ALOGV("st_dev = %llu", static_cast<uint64_t>(sb.st_dev));
Steve Block3856b092011-10-20 11:56:00 +0100744 ALOGV("st_mode = %u", sb.st_mode);
Mark Salyzyn77342f72014-06-18 16:31:32 -0700745 ALOGV("st_uid = %lu", static_cast<unsigned long>(sb.st_uid));
746 ALOGV("st_gid = %lu", static_cast<unsigned long>(sb.st_gid));
Steve Block3856b092011-10-20 11:56:00 +0100747 ALOGV("st_size = %llu", sb.st_size);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800748
749 if (offset >= sb.st_size) {
Steve Block29357bc2012-01-06 19:20:56 +0000750 ALOGE("offset error");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800751 ::close(fd);
752 return UNKNOWN_ERROR;
753 }
754 if (offset + length > sb.st_size) {
755 length = sb.st_size - offset;
Steve Block3856b092011-10-20 11:56:00 +0100756 ALOGV("calculated length = %lld", length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800757 }
758
John Grossman44a7e422012-06-21 17:29:24 -0700759 player_type playerType = MediaPlayerFactory::getPlayerType(this,
760 fd,
761 offset,
762 length);
John Grossmanc795b642012-02-22 15:38:35 -0800763 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
764 if (p == NULL) {
765 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800766 }
767
768 // now set data source
John Grossmanc795b642012-02-22 15:38:35 -0800769 setDataSource_post(p, p->setDataSource(fd, offset, length));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800770 return mStatus;
771}
772
Andreas Hubere2b10282010-11-23 11:41:34 -0800773status_t MediaPlayerService::Client::setDataSource(
774 const sp<IStreamSource> &source) {
775 // create the right type of player
John Grossman44a7e422012-06-21 17:29:24 -0700776 player_type playerType = MediaPlayerFactory::getPlayerType(this, source);
John Grossmanc795b642012-02-22 15:38:35 -0800777 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
Andreas Hubere2b10282010-11-23 11:41:34 -0800778 if (p == NULL) {
779 return NO_INIT;
780 }
781
Andreas Hubere2b10282010-11-23 11:41:34 -0800782 // now set data source
John Grossmanc795b642012-02-22 15:38:35 -0800783 setDataSource_post(p, p->setDataSource(source));
Andreas Hubere2b10282010-11-23 11:41:34 -0800784 return mStatus;
785}
786
Chris Watkins99f31602015-03-20 13:06:33 -0700787status_t MediaPlayerService::Client::setDataSource(
788 const sp<IDataSource> &source) {
789 sp<DataSource> dataSource = DataSource::CreateFromIDataSource(source);
790 player_type playerType = MediaPlayerFactory::getPlayerType(this, dataSource);
791 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
792 if (p == NULL) {
793 return NO_INIT;
794 }
795 // now set data source
796 setDataSource_post(p, p->setDataSource(dataSource));
797 return mStatus;
798}
799
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700800void MediaPlayerService::Client::disconnectNativeWindow() {
801 if (mConnectedWindow != NULL) {
802 status_t err = native_window_api_disconnect(mConnectedWindow.get(),
803 NATIVE_WINDOW_API_MEDIA);
804
805 if (err != OK) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000806 ALOGW("native_window_api_disconnect returned an error: %s (%d)",
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700807 strerror(-err), err);
808 }
809 }
810 mConnectedWindow.clear();
811}
812
Glenn Kasten11731182011-02-08 17:26:17 -0800813status_t MediaPlayerService::Client::setVideoSurfaceTexture(
Andy McFadden484566c2012-12-18 09:46:54 -0800814 const sp<IGraphicBufferProducer>& bufferProducer)
Glenn Kasten11731182011-02-08 17:26:17 -0800815{
Andy McFadden484566c2012-12-18 09:46:54 -0800816 ALOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, bufferProducer.get());
Glenn Kasten11731182011-02-08 17:26:17 -0800817 sp<MediaPlayerBase> p = getPlayer();
818 if (p == 0) return UNKNOWN_ERROR;
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700819
Marco Nelissenf8880202014-11-14 07:58:25 -0800820 sp<IBinder> binder(IInterface::asBinder(bufferProducer));
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700821 if (mConnectedWindowBinder == binder) {
822 return OK;
823 }
824
825 sp<ANativeWindow> anw;
Andy McFadden484566c2012-12-18 09:46:54 -0800826 if (bufferProducer != NULL) {
Marco Nelissenee08f7e2013-09-16 13:30:01 -0700827 anw = new Surface(bufferProducer, true /* controlledByApp */);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700828 status_t err = native_window_api_connect(anw.get(),
829 NATIVE_WINDOW_API_MEDIA);
830
831 if (err != OK) {
Steve Block29357bc2012-01-06 19:20:56 +0000832 ALOGE("setVideoSurfaceTexture failed: %d", err);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700833 // Note that we must do the reset before disconnecting from the ANW.
834 // Otherwise queue/dequeue calls could be made on the disconnected
835 // ANW, which may result in errors.
836 reset();
837
838 disconnectNativeWindow();
839
840 return err;
841 }
842 }
843
Andy McFadden484566c2012-12-18 09:46:54 -0800844 // Note that we must set the player's new GraphicBufferProducer before
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700845 // disconnecting the old one. Otherwise queue/dequeue calls could be made
846 // on the disconnected ANW, which may result in errors.
Andy McFadden484566c2012-12-18 09:46:54 -0800847 status_t err = p->setVideoSurfaceTexture(bufferProducer);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700848
849 disconnectNativeWindow();
850
851 mConnectedWindow = anw;
852
853 if (err == OK) {
854 mConnectedWindowBinder = binder;
855 } else {
856 disconnectNativeWindow();
857 }
858
859 return err;
Glenn Kasten11731182011-02-08 17:26:17 -0800860}
861
Nicolas Catania1d187f12009-05-12 23:25:55 -0700862status_t MediaPlayerService::Client::invoke(const Parcel& request,
863 Parcel *reply)
864{
865 sp<MediaPlayerBase> p = getPlayer();
866 if (p == NULL) return UNKNOWN_ERROR;
867 return p->invoke(request, reply);
868}
869
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700870// This call doesn't need to access the native player.
871status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
872{
873 status_t status;
nikoa64c8c72009-07-20 15:07:26 -0700874 media::Metadata::Filter allow, drop;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700875
Nicolas Catania48290382009-07-10 13:53:06 -0700876 if (unmarshallFilter(filter, &allow, &status) &&
877 unmarshallFilter(filter, &drop, &status)) {
878 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700879
880 mMetadataAllow = allow;
881 mMetadataDrop = drop;
882 }
883 return status;
884}
885
Nicolas Catania48290382009-07-10 13:53:06 -0700886status_t MediaPlayerService::Client::getMetadata(
Mark Salyzyn77342f72014-06-18 16:31:32 -0700887 bool update_only, bool /*apply_filter*/, Parcel *reply)
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700888{
nikoa64c8c72009-07-20 15:07:26 -0700889 sp<MediaPlayerBase> player = getPlayer();
890 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania48290382009-07-10 13:53:06 -0700891
nikod608a812009-07-16 16:39:53 -0700892 status_t status;
893 // Placeholder for the return code, updated by the caller.
894 reply->writeInt32(-1);
895
nikoa64c8c72009-07-20 15:07:26 -0700896 media::Metadata::Filter ids;
Nicolas Catania48290382009-07-10 13:53:06 -0700897
898 // We don't block notifications while we fetch the data. We clear
899 // mMetadataUpdated first so we don't lose notifications happening
900 // during the rest of this call.
901 {
902 Mutex::Autolock lock(mLock);
903 if (update_only) {
nikod608a812009-07-16 16:39:53 -0700904 ids = mMetadataUpdated;
Nicolas Catania48290382009-07-10 13:53:06 -0700905 }
906 mMetadataUpdated.clear();
907 }
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700908
nikoa64c8c72009-07-20 15:07:26 -0700909 media::Metadata metadata(reply);
Nicolas Catania48290382009-07-10 13:53:06 -0700910
nikoa64c8c72009-07-20 15:07:26 -0700911 metadata.appendHeader();
912 status = player->getMetadata(ids, reply);
nikod608a812009-07-16 16:39:53 -0700913
914 if (status != OK) {
nikoa64c8c72009-07-20 15:07:26 -0700915 metadata.resetParcel();
Steve Block29357bc2012-01-06 19:20:56 +0000916 ALOGE("getMetadata failed %d", status);
nikod608a812009-07-16 16:39:53 -0700917 return status;
918 }
919
920 // FIXME: Implement filtering on the result. Not critical since
921 // filtering takes place on the update notifications already. This
922 // would be when all the metadata are fetch and a filter is set.
923
nikod608a812009-07-16 16:39:53 -0700924 // Everything is fine, update the metadata length.
nikoa64c8c72009-07-20 15:07:26 -0700925 metadata.updateLength();
nikod608a812009-07-16 16:39:53 -0700926 return OK;
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700927}
928
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800929status_t MediaPlayerService::Client::prepareAsync()
930{
Steve Block3856b092011-10-20 11:56:00 +0100931 ALOGV("[%d] prepareAsync", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800932 sp<MediaPlayerBase> p = getPlayer();
933 if (p == 0) return UNKNOWN_ERROR;
934 status_t ret = p->prepareAsync();
935#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000936 ALOGD("start Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800937 if (ret == NO_ERROR) mAntagonizer->start();
938#endif
939 return ret;
940}
941
942status_t MediaPlayerService::Client::start()
943{
Steve Block3856b092011-10-20 11:56:00 +0100944 ALOGV("[%d] start", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800945 sp<MediaPlayerBase> p = getPlayer();
946 if (p == 0) return UNKNOWN_ERROR;
947 p->setLooping(mLoop);
948 return p->start();
949}
950
951status_t MediaPlayerService::Client::stop()
952{
Steve Block3856b092011-10-20 11:56:00 +0100953 ALOGV("[%d] stop", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800954 sp<MediaPlayerBase> p = getPlayer();
955 if (p == 0) return UNKNOWN_ERROR;
956 return p->stop();
957}
958
959status_t MediaPlayerService::Client::pause()
960{
Steve Block3856b092011-10-20 11:56:00 +0100961 ALOGV("[%d] pause", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800962 sp<MediaPlayerBase> p = getPlayer();
963 if (p == 0) return UNKNOWN_ERROR;
964 return p->pause();
965}
966
967status_t MediaPlayerService::Client::isPlaying(bool* state)
968{
969 *state = false;
970 sp<MediaPlayerBase> p = getPlayer();
971 if (p == 0) return UNKNOWN_ERROR;
972 *state = p->isPlaying();
Steve Block3856b092011-10-20 11:56:00 +0100973 ALOGV("[%d] isPlaying: %d", mConnId, *state);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800974 return NO_ERROR;
975}
976
Lajos Molnar3a474aa2015-04-24 17:10:07 -0700977status_t MediaPlayerService::Client::setPlaybackSettings(const AudioPlaybackRate& rate)
Wei Jia98160162015-02-04 17:01:11 -0800978{
Lajos Molnar3a474aa2015-04-24 17:10:07 -0700979 ALOGV("[%d] setPlaybackSettings(%f, %f, %d, %d)",
980 mConnId, rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Wei Jia98160162015-02-04 17:01:11 -0800981 sp<MediaPlayerBase> p = getPlayer();
982 if (p == 0) return UNKNOWN_ERROR;
Lajos Molnar3a474aa2015-04-24 17:10:07 -0700983 return p->setPlaybackSettings(rate);
984}
985
986status_t MediaPlayerService::Client::getPlaybackSettings(AudioPlaybackRate* rate /* nonnull */)
987{
988 sp<MediaPlayerBase> p = getPlayer();
989 if (p == 0) return UNKNOWN_ERROR;
990 status_t ret = p->getPlaybackSettings(rate);
991 if (ret == NO_ERROR) {
992 ALOGV("[%d] getPlaybackSettings(%f, %f, %d, %d)",
993 mConnId, rate->mSpeed, rate->mPitch, rate->mFallbackMode, rate->mStretchMode);
994 } else {
995 ALOGV("[%d] getPlaybackSettings returned %d", mConnId, ret);
996 }
997 return ret;
998}
999
1000status_t MediaPlayerService::Client::setSyncSettings(
1001 const AVSyncSettings& sync, float videoFpsHint)
1002{
1003 ALOGV("[%d] setSyncSettings(%u, %u, %f, %f)",
1004 mConnId, sync.mSource, sync.mAudioAdjustMode, sync.mTolerance, videoFpsHint);
1005 sp<MediaPlayerBase> p = getPlayer();
1006 if (p == 0) return UNKNOWN_ERROR;
1007 return p->setSyncSettings(sync, videoFpsHint);
1008}
1009
1010status_t MediaPlayerService::Client::getSyncSettings(
1011 AVSyncSettings* sync /* nonnull */, float* videoFps /* nonnull */)
1012{
1013 sp<MediaPlayerBase> p = getPlayer();
1014 if (p == 0) return UNKNOWN_ERROR;
1015 status_t ret = p->getSyncSettings(sync, videoFps);
1016 if (ret == NO_ERROR) {
1017 ALOGV("[%d] getSyncSettings(%u, %u, %f, %f)",
1018 mConnId, sync->mSource, sync->mAudioAdjustMode, sync->mTolerance, *videoFps);
1019 } else {
1020 ALOGV("[%d] getSyncSettings returned %d", mConnId, ret);
1021 }
1022 return ret;
Wei Jia98160162015-02-04 17:01:11 -08001023}
1024
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001025status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
1026{
Steve Block3856b092011-10-20 11:56:00 +01001027 ALOGV("getCurrentPosition");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001028 sp<MediaPlayerBase> p = getPlayer();
1029 if (p == 0) return UNKNOWN_ERROR;
1030 status_t ret = p->getCurrentPosition(msec);
1031 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001032 ALOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001033 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001034 ALOGE("getCurrentPosition returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001035 }
1036 return ret;
1037}
1038
1039status_t MediaPlayerService::Client::getDuration(int *msec)
1040{
Steve Block3856b092011-10-20 11:56:00 +01001041 ALOGV("getDuration");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001042 sp<MediaPlayerBase> p = getPlayer();
1043 if (p == 0) return UNKNOWN_ERROR;
1044 status_t ret = p->getDuration(msec);
1045 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001046 ALOGV("[%d] getDuration = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001047 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001048 ALOGE("getDuration returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001049 }
1050 return ret;
1051}
1052
Marco Nelissen6b74d672012-02-28 16:07:44 -08001053status_t MediaPlayerService::Client::setNextPlayer(const sp<IMediaPlayer>& player) {
1054 ALOGV("setNextPlayer");
1055 Mutex::Autolock l(mLock);
1056 sp<Client> c = static_cast<Client*>(player.get());
1057 mNextClient = c;
John Grossman5f7e55e2012-08-24 14:47:25 -07001058
1059 if (c != NULL) {
1060 if (mAudioOutput != NULL) {
1061 mAudioOutput->setNextOutput(c->mAudioOutput);
1062 } else if ((mPlayer != NULL) && !mPlayer->hardwareOutput()) {
1063 ALOGE("no current audio output");
1064 }
1065
1066 if ((mPlayer != NULL) && (mNextClient->getPlayer() != NULL)) {
1067 mPlayer->setNextPlayer(mNextClient->getPlayer());
1068 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001069 }
John Grossman5f7e55e2012-08-24 14:47:25 -07001070
Marco Nelissen6b74d672012-02-28 16:07:44 -08001071 return OK;
1072}
1073
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001074status_t MediaPlayerService::Client::seekTo(int msec)
1075{
Steve Block3856b092011-10-20 11:56:00 +01001076 ALOGV("[%d] seekTo(%d)", mConnId, msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001077 sp<MediaPlayerBase> p = getPlayer();
1078 if (p == 0) return UNKNOWN_ERROR;
1079 return p->seekTo(msec);
1080}
1081
1082status_t MediaPlayerService::Client::reset()
1083{
Steve Block3856b092011-10-20 11:56:00 +01001084 ALOGV("[%d] reset", mConnId);
John Grossmanc795b642012-02-22 15:38:35 -08001085 mRetransmitEndpointValid = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001086 sp<MediaPlayerBase> p = getPlayer();
1087 if (p == 0) return UNKNOWN_ERROR;
1088 return p->reset();
1089}
1090
Glenn Kastenfff6d712012-01-12 16:38:12 -08001091status_t MediaPlayerService::Client::setAudioStreamType(audio_stream_type_t type)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001092{
Steve Block3856b092011-10-20 11:56:00 +01001093 ALOGV("[%d] setAudioStreamType(%d)", mConnId, type);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001094 // TODO: for hardware output, call player instead
1095 Mutex::Autolock l(mLock);
1096 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1097 return NO_ERROR;
1098}
1099
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001100status_t MediaPlayerService::Client::setAudioAttributes_l(const Parcel &parcel)
1101{
1102 if (mAudioAttributes != NULL) { free(mAudioAttributes); }
1103 mAudioAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1104 unmarshallAudioAttributes(parcel, mAudioAttributes);
1105
1106 ALOGV("setAudioAttributes_l() usage=%d content=%d flags=0x%x tags=%s",
1107 mAudioAttributes->usage, mAudioAttributes->content_type, mAudioAttributes->flags,
1108 mAudioAttributes->tags);
1109
1110 if (mAudioOutput != 0) {
1111 mAudioOutput->setAudioAttributes(mAudioAttributes);
1112 }
1113 return NO_ERROR;
1114}
1115
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001116status_t MediaPlayerService::Client::setLooping(int loop)
1117{
Steve Block3856b092011-10-20 11:56:00 +01001118 ALOGV("[%d] setLooping(%d)", mConnId, loop);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001119 mLoop = loop;
1120 sp<MediaPlayerBase> p = getPlayer();
1121 if (p != 0) return p->setLooping(loop);
1122 return NO_ERROR;
1123}
1124
1125status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1126{
Steve Block3856b092011-10-20 11:56:00 +01001127 ALOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
John Grossman761defc2012-02-09 15:09:05 -08001128
1129 // for hardware output, call player instead
1130 sp<MediaPlayerBase> p = getPlayer();
1131 {
1132 Mutex::Autolock l(mLock);
1133 if (p != 0 && p->hardwareOutput()) {
1134 MediaPlayerHWInterface* hwp =
1135 reinterpret_cast<MediaPlayerHWInterface*>(p.get());
1136 return hwp->setVolume(leftVolume, rightVolume);
1137 } else {
1138 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1139 return NO_ERROR;
1140 }
1141 }
1142
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001143 return NO_ERROR;
1144}
1145
Eric Laurent2beeb502010-07-16 07:43:46 -07001146status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1147{
Steve Block3856b092011-10-20 11:56:00 +01001148 ALOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
Eric Laurent2beeb502010-07-16 07:43:46 -07001149 Mutex::Autolock l(mLock);
1150 if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1151 return NO_ERROR;
1152}
1153
1154status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1155{
Steve Block3856b092011-10-20 11:56:00 +01001156 ALOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
Eric Laurent2beeb502010-07-16 07:43:46 -07001157 Mutex::Autolock l(mLock);
1158 if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1159 return NO_ERROR;
1160}
Nicolas Catania48290382009-07-10 13:53:06 -07001161
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001162status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
Steve Block3856b092011-10-20 11:56:00 +01001163 ALOGV("[%d] setParameter(%d)", mConnId, key);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001164 switch (key) {
1165 case KEY_PARAMETER_AUDIO_ATTRIBUTES:
1166 {
1167 Mutex::Autolock l(mLock);
1168 return setAudioAttributes_l(request);
1169 }
1170 default:
1171 sp<MediaPlayerBase> p = getPlayer();
1172 if (p == 0) { return UNKNOWN_ERROR; }
1173 return p->setParameter(key, request);
1174 }
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001175}
1176
1177status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
Steve Block3856b092011-10-20 11:56:00 +01001178 ALOGV("[%d] getParameter(%d)", mConnId, key);
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001179 sp<MediaPlayerBase> p = getPlayer();
1180 if (p == 0) return UNKNOWN_ERROR;
1181 return p->getParameter(key, reply);
1182}
1183
John Grossmanc795b642012-02-22 15:38:35 -08001184status_t MediaPlayerService::Client::setRetransmitEndpoint(
1185 const struct sockaddr_in* endpoint) {
1186
1187 if (NULL != endpoint) {
1188 uint32_t a = ntohl(endpoint->sin_addr.s_addr);
1189 uint16_t p = ntohs(endpoint->sin_port);
1190 ALOGV("[%d] setRetransmitEndpoint(%u.%u.%u.%u:%hu)", mConnId,
1191 (a >> 24), (a >> 16) & 0xFF, (a >> 8) & 0xFF, (a & 0xFF), p);
1192 } else {
1193 ALOGV("[%d] setRetransmitEndpoint = <none>", mConnId);
1194 }
1195
1196 sp<MediaPlayerBase> p = getPlayer();
1197
1198 // Right now, the only valid time to set a retransmit endpoint is before
1199 // player selection has been made (since the presence or absence of a
1200 // retransmit endpoint is going to determine which player is selected during
1201 // setDataSource).
1202 if (p != 0) return INVALID_OPERATION;
1203
1204 if (NULL != endpoint) {
1205 mRetransmitEndpoint = *endpoint;
1206 mRetransmitEndpointValid = true;
1207 } else {
1208 mRetransmitEndpointValid = false;
1209 }
1210
1211 return NO_ERROR;
1212}
1213
John Grossman44a7e422012-06-21 17:29:24 -07001214status_t MediaPlayerService::Client::getRetransmitEndpoint(
1215 struct sockaddr_in* endpoint)
1216{
1217 if (NULL == endpoint)
1218 return BAD_VALUE;
1219
1220 sp<MediaPlayerBase> p = getPlayer();
1221
1222 if (p != NULL)
1223 return p->getRetransmitEndpoint(endpoint);
1224
1225 if (!mRetransmitEndpointValid)
1226 return NO_INIT;
1227
1228 *endpoint = mRetransmitEndpoint;
1229
1230 return NO_ERROR;
1231}
1232
Gloria Wangb483c472011-04-11 17:23:27 -07001233void MediaPlayerService::Client::notify(
1234 void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001235{
1236 Client* client = static_cast<Client*>(cookie);
James Dongb8a98252012-08-26 16:13:03 -07001237 if (client == NULL) {
1238 return;
1239 }
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001240
James Dongb8a98252012-08-26 16:13:03 -07001241 sp<IMediaPlayerClient> c;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001242 {
1243 Mutex::Autolock l(client->mLock);
James Dongb8a98252012-08-26 16:13:03 -07001244 c = client->mClient;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001245 if (msg == MEDIA_PLAYBACK_COMPLETE && client->mNextClient != NULL) {
John Grossmancb0b7552012-08-23 17:47:31 -07001246 if (client->mAudioOutput != NULL)
1247 client->mAudioOutput->switchToNextOutput();
Marco Nelissen6b74d672012-02-28 16:07:44 -08001248 client->mNextClient->start();
1249 client->mNextClient->mClient->notify(MEDIA_INFO, MEDIA_INFO_STARTED_AS_NEXT, 0, obj);
1250 }
1251 }
1252
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001253 if (MEDIA_INFO == msg &&
Nicolas Catania48290382009-07-10 13:53:06 -07001254 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikoa64c8c72009-07-20 15:07:26 -07001255 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania48290382009-07-10 13:53:06 -07001256
1257 if(client->shouldDropMetadata(metadata_type)) {
1258 return;
1259 }
1260
1261 // Update the list of metadata that have changed. getMetadata
1262 // also access mMetadataUpdated and clears it.
1263 client->addNewMetadataUpdate(metadata_type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001264 }
James Dongb8a98252012-08-26 16:13:03 -07001265
1266 if (c != NULL) {
1267 ALOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
1268 c->notify(msg, ext1, ext2, obj);
1269 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001270}
1271
Nicolas Catania48290382009-07-10 13:53:06 -07001272
nikoa64c8c72009-07-20 15:07:26 -07001273bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001274{
Nicolas Catania48290382009-07-10 13:53:06 -07001275 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001276
Nicolas Catania48290382009-07-10 13:53:06 -07001277 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001278 return true;
1279 }
1280
Nicolas Catania48290382009-07-10 13:53:06 -07001281 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001282 return false;
Nicolas Catania48290382009-07-10 13:53:06 -07001283 } else {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001284 return true;
1285 }
1286}
1287
Nicolas Catania48290382009-07-10 13:53:06 -07001288
nikoa64c8c72009-07-20 15:07:26 -07001289void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania48290382009-07-10 13:53:06 -07001290 Mutex::Autolock lock(mLock);
1291 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1292 mMetadataUpdated.add(metadata_type);
1293 }
1294}
1295
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001296#if CALLBACK_ANTAGONIZER
1297const int Antagonizer::interval = 10000; // 10 msecs
1298
1299Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1300 mExit(false), mActive(false), mClient(client), mCb(cb)
1301{
1302 createThread(callbackThread, this);
1303}
1304
1305void Antagonizer::kill()
1306{
1307 Mutex::Autolock _l(mLock);
1308 mActive = false;
1309 mExit = true;
1310 mCondition.wait(mLock);
1311}
1312
1313int Antagonizer::callbackThread(void* user)
1314{
Steve Blockb8a80522011-12-20 16:23:08 +00001315 ALOGD("Antagonizer started");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001316 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1317 while (!p->mExit) {
1318 if (p->mActive) {
Steve Block3856b092011-10-20 11:56:00 +01001319 ALOGV("send event");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001320 p->mCb(p->mClient, 0, 0, 0);
1321 }
1322 usleep(interval);
1323 }
1324 Mutex::Autolock _l(p->mLock);
1325 p->mCondition.signal();
Steve Blockb8a80522011-12-20 16:23:08 +00001326 ALOGD("Antagonizer stopped");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001327 return 0;
1328}
1329#endif
1330
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001331#undef LOG_TAG
1332#define LOG_TAG "AudioSink"
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001333MediaPlayerService::AudioOutput::AudioOutput(int sessionId, int uid, int pid,
1334 const audio_attributes_t* attr)
Andreas Huber20111aa2009-07-14 16:56:47 -07001335 : mCallback(NULL),
Eric Laurenta514bdb2010-06-21 09:27:30 -07001336 mCallbackCookie(NULL),
Marco Nelissen6b74d672012-02-28 16:07:44 -08001337 mCallbackData(NULL),
Marco Nelissen4110c102012-03-29 09:31:28 -07001338 mBytesWritten(0),
Andy Hungd1c74342015-07-07 16:54:23 -07001339 mStreamType(AUDIO_STREAM_MUSIC),
1340 mAttributes(attr),
1341 mLeftVolume(1.0),
1342 mRightVolume(1.0),
1343 mPlaybackRate(AUDIO_PLAYBACK_RATE_DEFAULT),
1344 mSampleRateHz(0),
1345 mMsecsPerFrame(0),
1346 mFrameSize(0),
Eric Laurent1948eb32012-04-13 16:50:19 -07001347 mSessionId(sessionId),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001348 mUid(uid),
Marco Nelissend457c972014-02-11 08:47:07 -08001349 mPid(pid),
Andy Hungd1c74342015-07-07 16:54:23 -07001350 mSendLevel(0.0),
1351 mAuxEffectId(0),
1352 mFlags(AUDIO_OUTPUT_FLAG_NONE)
1353{
Steve Block3856b092011-10-20 11:56:00 +01001354 ALOGV("AudioOutput(%d)", sessionId);
Eric Laurent43562692015-07-15 16:49:07 -07001355 if (attr != NULL) {
1356 mStreamType = audio_attributes_to_stream_type(attr);
1357 }
1358
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001359 setMinBufferCount();
1360}
1361
1362MediaPlayerService::AudioOutput::~AudioOutput()
1363{
1364 close();
Marco Nelissen6b74d672012-02-28 16:07:44 -08001365 delete mCallbackData;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001366}
1367
Andy Hungd1c74342015-07-07 16:54:23 -07001368//static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001369void MediaPlayerService::AudioOutput::setMinBufferCount()
1370{
1371 char value[PROPERTY_VALUE_MAX];
1372 if (property_get("ro.kernel.qemu", value, 0)) {
1373 mIsOnEmulator = true;
1374 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1375 }
1376}
1377
Andy Hungd1c74342015-07-07 16:54:23 -07001378// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001379bool MediaPlayerService::AudioOutput::isOnEmulator()
1380{
Andy Hungd1c74342015-07-07 16:54:23 -07001381 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001382 return mIsOnEmulator;
1383}
1384
Andy Hungd1c74342015-07-07 16:54:23 -07001385// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001386int MediaPlayerService::AudioOutput::getMinBufferCount()
1387{
Andy Hungd1c74342015-07-07 16:54:23 -07001388 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001389 return mMinBufferCount;
1390}
1391
1392ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1393{
Andy Hungd1c74342015-07-07 16:54:23 -07001394 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001395 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001396 return mTrack->frameCount() * mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001397}
1398
1399ssize_t MediaPlayerService::AudioOutput::frameCount() const
1400{
Andy Hungd1c74342015-07-07 16:54:23 -07001401 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001402 if (mTrack == 0) return NO_INIT;
1403 return mTrack->frameCount();
1404}
1405
1406ssize_t MediaPlayerService::AudioOutput::channelCount() const
1407{
Andy Hungd1c74342015-07-07 16:54:23 -07001408 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001409 if (mTrack == 0) return NO_INIT;
1410 return mTrack->channelCount();
1411}
1412
1413ssize_t MediaPlayerService::AudioOutput::frameSize() const
1414{
Andy Hungd1c74342015-07-07 16:54:23 -07001415 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001416 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001417 return mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001418}
1419
1420uint32_t MediaPlayerService::AudioOutput::latency () const
1421{
Andy Hungd1c74342015-07-07 16:54:23 -07001422 Mutex::Autolock lock(mLock);
Eric Laurentdb354e52012-03-05 17:27:11 -08001423 if (mTrack == 0) return 0;
1424 return mTrack->latency();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001425}
1426
1427float MediaPlayerService::AudioOutput::msecsPerFrame() const
1428{
Andy Hungd1c74342015-07-07 16:54:23 -07001429 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001430 return mMsecsPerFrame;
1431}
1432
Marco Nelissen4110c102012-03-29 09:31:28 -07001433status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position) const
Eric Laurent342e9cf2010-01-19 17:37:09 -08001434{
Andy Hungd1c74342015-07-07 16:54:23 -07001435 Mutex::Autolock lock(mLock);
Eric Laurent342e9cf2010-01-19 17:37:09 -08001436 if (mTrack == 0) return NO_INIT;
1437 return mTrack->getPosition(position);
1438}
1439
Lajos Molnar06ad1522014-08-28 07:27:44 -07001440status_t MediaPlayerService::AudioOutput::getTimestamp(AudioTimestamp &ts) const
1441{
Andy Hungd1c74342015-07-07 16:54:23 -07001442 Mutex::Autolock lock(mLock);
Lajos Molnar06ad1522014-08-28 07:27:44 -07001443 if (mTrack == 0) return NO_INIT;
1444 return mTrack->getTimestamp(ts);
1445}
1446
Marco Nelissen4110c102012-03-29 09:31:28 -07001447status_t MediaPlayerService::AudioOutput::getFramesWritten(uint32_t *frameswritten) const
1448{
Andy Hungd1c74342015-07-07 16:54:23 -07001449 Mutex::Autolock lock(mLock);
Marco Nelissen4110c102012-03-29 09:31:28 -07001450 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001451 *frameswritten = mBytesWritten / mFrameSize;
Marco Nelissen4110c102012-03-29 09:31:28 -07001452 return OK;
1453}
1454
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001455status_t MediaPlayerService::AudioOutput::setParameters(const String8& keyValuePairs)
1456{
Andy Hungd1c74342015-07-07 16:54:23 -07001457 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001458 if (mTrack == 0) return NO_INIT;
1459 return mTrack->setParameters(keyValuePairs);
1460}
1461
1462String8 MediaPlayerService::AudioOutput::getParameters(const String8& keys)
1463{
Andy Hungd1c74342015-07-07 16:54:23 -07001464 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001465 if (mTrack == 0) return String8::empty();
1466 return mTrack->getParameters(keys);
1467}
1468
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001469void MediaPlayerService::AudioOutput::setAudioAttributes(const audio_attributes_t * attributes) {
Andy Hungd1c74342015-07-07 16:54:23 -07001470 Mutex::Autolock lock(mLock);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001471 mAttributes = attributes;
Eric Laurent43562692015-07-15 16:49:07 -07001472 if (attributes != NULL) {
1473 mStreamType = audio_attributes_to_stream_type(attributes);
1474 }
1475}
1476
1477void MediaPlayerService::AudioOutput::setAudioStreamType(audio_stream_type_t streamType)
1478{
1479 // do not allow direct stream type modification if attributes have been set
1480 if (mAttributes == NULL) {
1481 mStreamType = streamType;
1482 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001483}
1484
Andy Hungd1c74342015-07-07 16:54:23 -07001485void MediaPlayerService::AudioOutput::deleteRecycledTrack_l()
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001486{
Andy Hungd1c74342015-07-07 16:54:23 -07001487 ALOGV("deleteRecycledTrack_l");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001488 if (mRecycledTrack != 0) {
1489
1490 if (mCallbackData != NULL) {
1491 mCallbackData->setOutput(NULL);
1492 mCallbackData->endTrackSwitch();
1493 }
1494
1495 if ((mRecycledTrack->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) {
1496 mRecycledTrack->flush();
1497 }
1498 // An offloaded track isn't flushed because the STREAM_END is reported
1499 // slightly prematurely to allow time for the gapless track switch
1500 // but this means that if we decide not to recycle the track there
1501 // could be a small amount of residual data still playing. We leave
1502 // AudioFlinger to drain the track.
1503
1504 mRecycledTrack.clear();
Andy Hungd1c74342015-07-07 16:54:23 -07001505 close_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001506 delete mCallbackData;
1507 mCallbackData = NULL;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001508 }
1509}
1510
Andy Hungd1c74342015-07-07 16:54:23 -07001511void MediaPlayerService::AudioOutput::close_l()
1512{
1513 mTrack.clear();
1514}
1515
Andreas Huber20111aa2009-07-14 16:56:47 -07001516status_t MediaPlayerService::AudioOutput::open(
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001517 uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
1518 audio_format_t format, int bufferCount,
Eric Laurent1948eb32012-04-13 16:50:19 -07001519 AudioCallback cb, void *cookie,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001520 audio_output_flags_t flags,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001521 const audio_offload_info_t *offloadInfo,
Andy Hung179652e2015-05-31 22:49:46 -07001522 bool doNotReconnect,
1523 uint32_t suggestedFrameCount)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001524{
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001525 ALOGV("open(%u, %d, 0x%x, 0x%x, %d, %d 0x%x)", sampleRate, channelCount, channelMask,
1526 format, bufferCount, mSessionId, flags);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001527
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001528 // offloading is only supported in callback mode for now.
1529 // offloadInfo must be present if offload flag is set
1530 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) &&
1531 ((cb == NULL) || (offloadInfo == NULL))) {
1532 return BAD_VALUE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001533 }
1534
Andy Hung179652e2015-05-31 22:49:46 -07001535 // compute frame count for the AudioTrack internal buffer
1536 size_t frameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001537 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1538 frameCount = 0; // AudioTrack will get frame count from AudioFlinger
1539 } else {
Andy Hung179652e2015-05-31 22:49:46 -07001540 // try to estimate the buffer processing fetch size from AudioFlinger.
1541 // framesPerBuffer is approximate and generally correct, except when it's not :-).
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001542 uint32_t afSampleRate;
1543 size_t afFrameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001544 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1545 return NO_INIT;
1546 }
1547 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1548 return NO_INIT;
1549 }
Andy Hung179652e2015-05-31 22:49:46 -07001550 const size_t framesPerBuffer =
1551 (unsigned long long)sampleRate * afFrameCount / afSampleRate;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001552
Andy Hung179652e2015-05-31 22:49:46 -07001553 if (bufferCount == 0) {
1554 // use suggestedFrameCount
1555 bufferCount = (suggestedFrameCount + framesPerBuffer - 1) / framesPerBuffer;
1556 }
1557 // Check argument bufferCount against the mininum buffer count
1558 if (bufferCount != 0 && bufferCount < mMinBufferCount) {
1559 ALOGV("bufferCount (%d) increased to %d", bufferCount, mMinBufferCount);
1560 bufferCount = mMinBufferCount;
1561 }
1562 // if frameCount is 0, then AudioTrack will get frame count from AudioFlinger
1563 // which will be the minimum size permitted.
1564 frameCount = bufferCount * framesPerBuffer;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001565 }
Andreas Huber20111aa2009-07-14 16:56:47 -07001566
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001567 if (channelMask == CHANNEL_MASK_USE_CHANNEL_ORDER) {
Glenn Kastenab334fd2012-03-14 12:56:06 -07001568 channelMask = audio_channel_out_mask_from_count(channelCount);
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001569 if (0 == channelMask) {
1570 ALOGE("open() error, can\'t derive mask for %d audio channels", channelCount);
1571 return NO_INIT;
1572 }
1573 }
Eric Laurent1948eb32012-04-13 16:50:19 -07001574
Andy Hungd1c74342015-07-07 16:54:23 -07001575 Mutex::Autolock lock(mLock);
Andy Hung179652e2015-05-31 22:49:46 -07001576 mCallback = cb;
1577 mCallbackCookie = cookie;
1578
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001579 // Check whether we can recycle the track
1580 bool reuse = false;
1581 bool bothOffloaded = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001582
Glenn Kasten2799d742013-05-30 14:33:29 -07001583 if (mRecycledTrack != 0) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001584 // check whether we are switching between two offloaded tracks
1585 bothOffloaded = (flags & mRecycledTrack->getFlags()
1586 & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0;
Marco Nelissen67295b52012-06-11 14:52:53 -07001587
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001588 // check if the existing track can be reused as-is, or if a new track needs to be created.
1589 reuse = true;
1590
Marco Nelissen67295b52012-06-11 14:52:53 -07001591 if ((mCallbackData == NULL && mCallback != NULL) ||
1592 (mCallbackData != NULL && mCallback == NULL)) {
1593 // recycled track uses callbacks but the caller wants to use writes, or vice versa
1594 ALOGV("can't chain callback and write");
1595 reuse = false;
1596 } else if ((mRecycledTrack->getSampleRate() != sampleRate) ||
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001597 (mRecycledTrack->channelCount() != (uint32_t)channelCount) ) {
1598 ALOGV("samplerate, channelcount differ: %u/%u Hz, %u/%d ch",
Marco Nelissen67295b52012-06-11 14:52:53 -07001599 mRecycledTrack->getSampleRate(), sampleRate,
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001600 mRecycledTrack->channelCount(), channelCount);
Marco Nelissen67295b52012-06-11 14:52:53 -07001601 reuse = false;
1602 } else if (flags != mFlags) {
1603 ALOGV("output flags differ %08x/%08x", flags, mFlags);
1604 reuse = false;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001605 } else if (mRecycledTrack->format() != format) {
1606 reuse = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001607 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001608 } else {
1609 ALOGV("no track available to recycle");
1610 }
1611
1612 ALOGV_IF(bothOffloaded, "both tracks offloaded");
1613
1614 // If we can't recycle and both tracks are offloaded
1615 // we must close the previous output before opening a new one
1616 if (bothOffloaded && !reuse) {
1617 ALOGV("both offloaded and not recycling");
Andy Hungd1c74342015-07-07 16:54:23 -07001618 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001619 }
1620
1621 sp<AudioTrack> t;
1622 CallbackData *newcbd = NULL;
1623
1624 // We don't attempt to create a new track if we are recycling an
1625 // offloaded track. But, if we are recycling a non-offloaded or we
1626 // are switching where one is offloaded and one isn't then we create
1627 // the new track in advance so that we can read additional stream info
1628
1629 if (!(reuse && bothOffloaded)) {
1630 ALOGV("creating new AudioTrack");
1631
1632 if (mCallback != NULL) {
1633 newcbd = new CallbackData(this);
1634 t = new AudioTrack(
1635 mStreamType,
1636 sampleRate,
1637 format,
1638 channelMask,
1639 frameCount,
1640 flags,
1641 CallbackWrapper,
1642 newcbd,
1643 0, // notification frames
1644 mSessionId,
1645 AudioTrack::TRANSFER_CALLBACK,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001646 offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -08001647 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001648 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001649 mAttributes,
1650 doNotReconnect);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001651 } else {
1652 t = new AudioTrack(
1653 mStreamType,
1654 sampleRate,
1655 format,
1656 channelMask,
1657 frameCount,
1658 flags,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001659 NULL, // callback
1660 NULL, // user data
1661 0, // notification frames
1662 mSessionId,
1663 AudioTrack::TRANSFER_DEFAULT,
1664 NULL, // offload info
Marco Nelissend457c972014-02-11 08:47:07 -08001665 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001666 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001667 mAttributes,
1668 doNotReconnect);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001669 }
1670
1671 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1672 ALOGE("Unable to create audio track");
1673 delete newcbd;
Glenn Kasten3e98ecd2015-05-18 13:13:24 -07001674 // t goes out of scope, so reference count drops to zero
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001675 return NO_INIT;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001676 } else {
1677 // successful AudioTrack initialization implies a legacy stream type was generated
1678 // from the audio attributes
1679 mStreamType = t->streamType();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001680 }
1681 }
1682
1683 if (reuse) {
1684 CHECK(mRecycledTrack != NULL);
1685
1686 if (!bothOffloaded) {
1687 if (mRecycledTrack->frameCount() != t->frameCount()) {
1688 ALOGV("framecount differs: %u/%u frames",
1689 mRecycledTrack->frameCount(), t->frameCount());
1690 reuse = false;
1691 }
1692 }
1693
Marco Nelissen67295b52012-06-11 14:52:53 -07001694 if (reuse) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001695 ALOGV("chaining to next output and recycling track");
Andy Hungd1c74342015-07-07 16:54:23 -07001696 close_l();
Marco Nelissen67295b52012-06-11 14:52:53 -07001697 mTrack = mRecycledTrack;
Glenn Kasten2799d742013-05-30 14:33:29 -07001698 mRecycledTrack.clear();
Marco Nelissen67295b52012-06-11 14:52:53 -07001699 if (mCallbackData != NULL) {
1700 mCallbackData->setOutput(this);
1701 }
Marco Nelissen67295b52012-06-11 14:52:53 -07001702 delete newcbd;
1703 return OK;
1704 }
Marco Nelissen67295b52012-06-11 14:52:53 -07001705 }
1706
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001707 // we're not going to reuse the track, unblock and flush it
1708 // this was done earlier if both tracks are offloaded
1709 if (!bothOffloaded) {
Andy Hungd1c74342015-07-07 16:54:23 -07001710 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001711 }
1712
1713 CHECK((t != NULL) && ((mCallback == NULL) || (newcbd != NULL)));
1714
Marco Nelissen67295b52012-06-11 14:52:53 -07001715 mCallbackData = newcbd;
Steve Block3856b092011-10-20 11:56:00 +01001716 ALOGV("setVolume");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001717 t->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07001718
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001719 mSampleRateHz = sampleRate;
Wei Jia0162d002015-06-09 11:59:33 -07001720 mFlags = t->getFlags(); // we suggest the flags above, but new AudioTrack() may not grant it.
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001721 mMsecsPerFrame = 1E3f / (mPlaybackRate.mSpeed * sampleRate);
Andy Hungd1c74342015-07-07 16:54:23 -07001722 mFrameSize = t->frameSize();
Marco Nelissen99448602012-04-02 12:16:49 -07001723 uint32_t pos;
1724 if (t->getPosition(&pos) == OK) {
Andy Hungd1c74342015-07-07 16:54:23 -07001725 mBytesWritten = uint64_t(pos) * mFrameSize;
Marco Nelissen99448602012-04-02 12:16:49 -07001726 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001727 mTrack = t;
Eric Laurent2beeb502010-07-16 07:43:46 -07001728
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001729 status_t res = NO_ERROR;
Wei Jia0162d002015-06-09 11:59:33 -07001730 // Note some output devices may give us a direct track even though we don't specify it.
1731 // Example: Line application b/17459982.
1732 if ((mFlags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) {
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001733 res = t->setPlaybackRate(mPlaybackRate);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001734 if (res == NO_ERROR) {
1735 t->setAuxEffectSendLevel(mSendLevel);
1736 res = t->attachAuxEffect(mAuxEffectId);
1737 }
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001738 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001739 ALOGV("open() DONE status %d", res);
1740 return res;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001741}
1742
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001743status_t MediaPlayerService::AudioOutput::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001744{
Steve Block3856b092011-10-20 11:56:00 +01001745 ALOGV("start");
Andy Hungd1c74342015-07-07 16:54:23 -07001746 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001747 if (mCallbackData != NULL) {
1748 mCallbackData->endTrackSwitch();
1749 }
Glenn Kasten2799d742013-05-30 14:33:29 -07001750 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001751 mTrack->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07001752 mTrack->setAuxEffectSendLevel(mSendLevel);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001753 return mTrack->start();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001754 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001755 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001756}
1757
Marco Nelissen6b74d672012-02-28 16:07:44 -08001758void MediaPlayerService::AudioOutput::setNextOutput(const sp<AudioOutput>& nextOutput) {
Andy Hungd1c74342015-07-07 16:54:23 -07001759 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001760 mNextOutput = nextOutput;
1761}
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08001762
Marco Nelissen6b74d672012-02-28 16:07:44 -08001763void MediaPlayerService::AudioOutput::switchToNextOutput() {
1764 ALOGV("switchToNextOutput");
Andy Hungd1c74342015-07-07 16:54:23 -07001765
1766 // Try to acquire the callback lock before moving track (without incurring deadlock).
1767 const unsigned kMaxSwitchTries = 100;
1768 Mutex::Autolock lock(mLock);
1769 for (unsigned tries = 0;;) {
1770 if (mTrack == 0) {
1771 return;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001772 }
Andy Hungd1c74342015-07-07 16:54:23 -07001773 if (mNextOutput != NULL && mNextOutput != this) {
1774 if (mCallbackData != NULL) {
1775 // two alternative approaches
1776#if 1
1777 CallbackData *callbackData = mCallbackData;
1778 mLock.unlock();
1779 // proper acquisition sequence
1780 callbackData->lock();
1781 mLock.lock();
1782 // Caution: it is unlikely that someone deleted our callback or changed our target
1783 if (callbackData != mCallbackData || mNextOutput == NULL || mNextOutput == this) {
1784 // fatal if we are starved out.
1785 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
1786 "switchToNextOutput() cannot obtain correct lock sequence");
1787 callbackData->unlock();
1788 continue;
1789 }
1790 callbackData->mSwitching = true; // begin track switch
1791#else
1792 // tryBeginTrackSwitch() returns false if the callback has the lock.
1793 if (!mCallbackData->tryBeginTrackSwitch()) {
1794 // fatal if we are starved out.
1795 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
1796 "switchToNextOutput() cannot obtain callback lock");
1797 mLock.unlock();
1798 usleep(5 * 1000 /* usec */); // allow callback to use AudioOutput
1799 mLock.lock();
1800 continue;
1801 }
1802#endif
1803 }
1804
1805 Mutex::Autolock nextLock(mNextOutput->mLock);
1806
1807 // If the next output track is not NULL, then it has been
1808 // opened already for playback.
1809 // This is possible even without the next player being started,
1810 // for example, the next player could be prepared and seeked.
1811 //
1812 // Presuming it isn't advisable to force the track over.
1813 if (mNextOutput->mTrack == NULL) {
1814 ALOGD("Recycling track for gapless playback");
1815 delete mNextOutput->mCallbackData;
1816 mNextOutput->mCallbackData = mCallbackData;
1817 mNextOutput->mRecycledTrack = mTrack;
1818 mNextOutput->mSampleRateHz = mSampleRateHz;
1819 mNextOutput->mMsecsPerFrame = mMsecsPerFrame;
1820 mNextOutput->mBytesWritten = mBytesWritten;
1821 mNextOutput->mFlags = mFlags;
1822 mNextOutput->mFrameSize = mFrameSize;
1823 close_l();
1824 mCallbackData = NULL; // destruction handled by mNextOutput
1825 } else {
1826 ALOGW("Ignoring gapless playback because next player has already started");
1827 // remove track in case resource needed for future players.
1828 if (mCallbackData != NULL) {
1829 mCallbackData->endTrackSwitch(); // release lock for callbacks before close.
1830 }
1831 close_l();
1832 }
1833 }
1834 break;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001835 }
1836}
1837
Wei Jia7d3f4df2015-03-03 15:28:00 -08001838ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001839{
Andy Hungd1c74342015-07-07 16:54:23 -07001840 Mutex::Autolock lock(mLock);
Glenn Kastenadad3d72014-02-21 14:51:43 -08001841 LOG_ALWAYS_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
Andreas Huber20111aa2009-07-14 16:56:47 -07001842
Steve Block3856b092011-10-20 11:56:00 +01001843 //ALOGV("write(%p, %u)", buffer, size);
Glenn Kasten2799d742013-05-30 14:33:29 -07001844 if (mTrack != 0) {
Wei Jia7d3f4df2015-03-03 15:28:00 -08001845 ssize_t ret = mTrack->write(buffer, size, blocking);
Andy Hunga31335a2014-08-20 17:37:59 -07001846 if (ret >= 0) {
1847 mBytesWritten += ret;
1848 }
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001849 return ret;
1850 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001851 return NO_INIT;
1852}
1853
1854void MediaPlayerService::AudioOutput::stop()
1855{
Steve Block3856b092011-10-20 11:56:00 +01001856 ALOGV("stop");
Andy Hungd1c74342015-07-07 16:54:23 -07001857 Mutex::Autolock lock(mLock);
Andy Hungda17c042015-06-01 15:53:14 -07001858 mBytesWritten = 0;
Glenn Kasten2799d742013-05-30 14:33:29 -07001859 if (mTrack != 0) mTrack->stop();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001860}
1861
1862void MediaPlayerService::AudioOutput::flush()
1863{
Steve Block3856b092011-10-20 11:56:00 +01001864 ALOGV("flush");
Andy Hungd1c74342015-07-07 16:54:23 -07001865 Mutex::Autolock lock(mLock);
Andy Hungda17c042015-06-01 15:53:14 -07001866 mBytesWritten = 0;
Glenn Kasten2799d742013-05-30 14:33:29 -07001867 if (mTrack != 0) mTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001868}
1869
1870void MediaPlayerService::AudioOutput::pause()
1871{
Steve Block3856b092011-10-20 11:56:00 +01001872 ALOGV("pause");
Andy Hungd1c74342015-07-07 16:54:23 -07001873 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07001874 if (mTrack != 0) mTrack->pause();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001875}
1876
1877void MediaPlayerService::AudioOutput::close()
1878{
Steve Block3856b092011-10-20 11:56:00 +01001879 ALOGV("close");
Andy Hungd1c74342015-07-07 16:54:23 -07001880 Mutex::Autolock lock(mLock);
1881 close_l();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001882}
1883
1884void MediaPlayerService::AudioOutput::setVolume(float left, float right)
1885{
Steve Block3856b092011-10-20 11:56:00 +01001886 ALOGV("setVolume(%f, %f)", left, right);
Andy Hungd1c74342015-07-07 16:54:23 -07001887 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001888 mLeftVolume = left;
1889 mRightVolume = right;
Glenn Kasten2799d742013-05-30 14:33:29 -07001890 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001891 mTrack->setVolume(left, right);
1892 }
1893}
1894
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001895status_t MediaPlayerService::AudioOutput::setPlaybackRate(const AudioPlaybackRate &rate)
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001896{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001897 ALOGV("setPlaybackRate(%f %f %d %d)",
1898 rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Andy Hungd1c74342015-07-07 16:54:23 -07001899 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001900 if (mTrack == 0) {
1901 // remember rate so that we can set it when the track is opened
1902 mPlaybackRate = rate;
1903 return OK;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001904 }
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001905 status_t res = mTrack->setPlaybackRate(rate);
1906 if (res != NO_ERROR) {
1907 return res;
1908 }
1909 // rate.mSpeed is always greater than 0 if setPlaybackRate succeeded
1910 CHECK_GT(rate.mSpeed, 0.f);
1911 mPlaybackRate = rate;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001912 if (mSampleRateHz != 0) {
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001913 mMsecsPerFrame = 1E3f / (rate.mSpeed * mSampleRateHz);
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001914 }
1915 return res;
1916}
1917
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001918status_t MediaPlayerService::AudioOutput::getPlaybackRate(AudioPlaybackRate *rate)
1919{
1920 ALOGV("setPlaybackRate");
Andy Hungd1c74342015-07-07 16:54:23 -07001921 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001922 if (mTrack == 0) {
1923 return NO_INIT;
1924 }
1925 *rate = mTrack->getPlaybackRate();
1926 return NO_ERROR;
1927}
1928
Eric Laurent2beeb502010-07-16 07:43:46 -07001929status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
1930{
Steve Block3856b092011-10-20 11:56:00 +01001931 ALOGV("setAuxEffectSendLevel(%f)", level);
Andy Hungd1c74342015-07-07 16:54:23 -07001932 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07001933 mSendLevel = level;
Glenn Kasten2799d742013-05-30 14:33:29 -07001934 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07001935 return mTrack->setAuxEffectSendLevel(level);
1936 }
1937 return NO_ERROR;
1938}
1939
1940status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
1941{
Steve Block3856b092011-10-20 11:56:00 +01001942 ALOGV("attachAuxEffect(%d)", effectId);
Andy Hungd1c74342015-07-07 16:54:23 -07001943 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07001944 mAuxEffectId = effectId;
Glenn Kasten2799d742013-05-30 14:33:29 -07001945 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07001946 return mTrack->attachAuxEffect(effectId);
1947 }
1948 return NO_ERROR;
1949}
1950
Andreas Huber20111aa2009-07-14 16:56:47 -07001951// static
1952void MediaPlayerService::AudioOutput::CallbackWrapper(
Glenn Kastend217a8c2011-06-01 15:20:35 -07001953 int event, void *cookie, void *info) {
Steve Block3856b092011-10-20 11:56:00 +01001954 //ALOGV("callbackwrapper");
Marco Nelissen6b74d672012-02-28 16:07:44 -08001955 CallbackData *data = (CallbackData*)cookie;
Andy Hungd1c74342015-07-07 16:54:23 -07001956 // lock to ensure we aren't caught in the middle of a track switch.
Marco Nelissen6b74d672012-02-28 16:07:44 -08001957 data->lock();
1958 AudioOutput *me = data->getOutput();
Andreas Huber20111aa2009-07-14 16:56:47 -07001959 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001960 if (me == NULL) {
1961 // no output set, likely because the track was scheduled to be reused
1962 // by another player, but the format turned out to be incompatible.
1963 data->unlock();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001964 if (buffer != NULL) {
1965 buffer->size = 0;
1966 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001967 return;
1968 }
Andreas Huber20111aa2009-07-14 16:56:47 -07001969
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001970 switch(event) {
1971 case AudioTrack::EVENT_MORE_DATA: {
1972 size_t actualSize = (*me->mCallback)(
1973 me, buffer->raw, buffer->size, me->mCallbackCookie,
1974 CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08001975
Andy Hung719b46b2015-05-31 22:18:25 -07001976 // Log when no data is returned from the callback.
1977 // (1) We may have no data (especially with network streaming sources).
1978 // (2) We may have reached the EOS and the audio track is not stopped yet.
1979 // Note that AwesomePlayer/AudioPlayer will only return zero size when it reaches the EOS.
1980 // NuPlayerRenderer will return zero when it doesn't have data (it doesn't block to fill).
1981 //
1982 // This is a benign busy-wait, with the next data request generated 10 ms or more later;
1983 // nevertheless for power reasons, we don't want to see too many of these.
Andreas Huber2e8ffaf2010-02-18 16:45:13 -08001984
Andy Hung719b46b2015-05-31 22:18:25 -07001985 ALOGV_IF(actualSize == 0 && buffer->size > 0, "callbackwrapper: empty buffer returned");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001986
Andy Hung719b46b2015-05-31 22:18:25 -07001987 me->mBytesWritten += actualSize; // benign race with reader.
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001988 buffer->size = actualSize;
1989 } break;
1990
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001991 case AudioTrack::EVENT_STREAM_END:
Andy Hung719b46b2015-05-31 22:18:25 -07001992 // currently only occurs for offloaded callbacks
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001993 ALOGV("callbackwrapper: deliver EVENT_STREAM_END");
1994 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
1995 me->mCallbackCookie, CB_EVENT_STREAM_END);
1996 break;
1997
1998 case AudioTrack::EVENT_NEW_IAUDIOTRACK :
1999 ALOGV("callbackwrapper: deliver EVENT_TEAR_DOWN");
2000 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2001 me->mCallbackCookie, CB_EVENT_TEAR_DOWN);
2002 break;
2003
Glenn Kasten421743b2015-06-01 08:18:08 -07002004 case AudioTrack::EVENT_UNDERRUN:
Andy Hung719b46b2015-05-31 22:18:25 -07002005 // This occurs when there is no data available, typically
Glenn Kasten421743b2015-06-01 08:18:08 -07002006 // when there is a failure to supply data to the AudioTrack. It can also
2007 // occur in non-offloaded mode when the audio device comes out of standby.
2008 //
Andy Hung719b46b2015-05-31 22:18:25 -07002009 // If an AudioTrack underruns it outputs silence. Since this happens suddenly
2010 // it may sound like an audible pop or glitch.
2011 //
2012 // The underrun event is sent once per track underrun; the condition is reset
2013 // when more data is sent to the AudioTrack.
Glenn Kasten421743b2015-06-01 08:18:08 -07002014 ALOGI("callbackwrapper: EVENT_UNDERRUN (discarded)");
2015 break;
2016
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002017 default:
2018 ALOGE("received unknown event type: %d inside CallbackWrapper !", event);
Andreas Huber51c1e0e2011-04-04 11:43:40 -07002019 }
2020
Marco Nelissen6b74d672012-02-28 16:07:44 -08002021 data->unlock();
Andreas Huber20111aa2009-07-14 16:56:47 -07002022}
2023
Marco Nelissen4110c102012-03-29 09:31:28 -07002024int MediaPlayerService::AudioOutput::getSessionId() const
Eric Laurent8c563ed2010-10-07 18:23:03 -07002025{
Andy Hungd1c74342015-07-07 16:54:23 -07002026 Mutex::Autolock lock(mLock);
Eric Laurent8c563ed2010-10-07 18:23:03 -07002027 return mSessionId;
2028}
2029
Eric Laurent6f59db12013-07-26 17:16:50 -07002030uint32_t MediaPlayerService::AudioOutput::getSampleRate() const
2031{
Andy Hungd1c74342015-07-07 16:54:23 -07002032 Mutex::Autolock lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -07002033 if (mTrack == 0) return 0;
2034 return mTrack->getSampleRate();
2035}
2036
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002037////////////////////////////////////////////////////////////////////////////////
2038
2039struct CallbackThread : public Thread {
2040 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
2041 MediaPlayerBase::AudioSink::AudioCallback cb,
2042 void *cookie);
2043
2044protected:
2045 virtual ~CallbackThread();
2046
2047 virtual bool threadLoop();
2048
2049private:
2050 wp<MediaPlayerBase::AudioSink> mSink;
2051 MediaPlayerBase::AudioSink::AudioCallback mCallback;
2052 void *mCookie;
2053 void *mBuffer;
2054 size_t mBufferSize;
2055
2056 CallbackThread(const CallbackThread &);
2057 CallbackThread &operator=(const CallbackThread &);
2058};
2059
2060CallbackThread::CallbackThread(
2061 const wp<MediaPlayerBase::AudioSink> &sink,
2062 MediaPlayerBase::AudioSink::AudioCallback cb,
2063 void *cookie)
2064 : mSink(sink),
2065 mCallback(cb),
2066 mCookie(cookie),
2067 mBuffer(NULL),
2068 mBufferSize(0) {
2069}
2070
2071CallbackThread::~CallbackThread() {
2072 if (mBuffer) {
2073 free(mBuffer);
2074 mBuffer = NULL;
2075 }
2076}
2077
2078bool CallbackThread::threadLoop() {
2079 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
2080 if (sink == NULL) {
2081 return false;
2082 }
2083
2084 if (mBuffer == NULL) {
2085 mBufferSize = sink->bufferSize();
2086 mBuffer = malloc(mBufferSize);
2087 }
2088
2089 size_t actualSize =
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002090 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie,
2091 MediaPlayerBase::AudioSink::CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002092
2093 if (actualSize > 0) {
2094 sink->write(mBuffer, actualSize);
Andy Hunga31335a2014-08-20 17:37:59 -07002095 // Could return false on sink->write() error or short count.
2096 // Not necessarily appropriate but would work for AudioCache behavior.
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002097 }
2098
2099 return true;
2100}
2101
2102////////////////////////////////////////////////////////////////////////////////
2103
Gloria Wang7cf180c2011-02-19 18:37:57 -08002104void MediaPlayerService::addBatteryData(uint32_t params)
2105{
2106 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002107
2108 int32_t time = systemTime() / 1000000L;
2109
2110 // change audio output devices. This notification comes from AudioFlinger
2111 if ((params & kBatteryDataSpeakerOn)
2112 || (params & kBatteryDataOtherAudioDeviceOn)) {
2113
2114 int deviceOn[NUM_AUDIO_DEVICES];
2115 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2116 deviceOn[i] = 0;
2117 }
2118
2119 if ((params & kBatteryDataSpeakerOn)
2120 && (params & kBatteryDataOtherAudioDeviceOn)) {
2121 deviceOn[SPEAKER_AND_OTHER] = 1;
2122 } else if (params & kBatteryDataSpeakerOn) {
2123 deviceOn[SPEAKER] = 1;
2124 } else {
2125 deviceOn[OTHER_AUDIO_DEVICE] = 1;
2126 }
2127
2128 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2129 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
2130
2131 if (mBatteryAudio.refCount > 0) { // if playing audio
2132 if (!deviceOn[i]) {
2133 mBatteryAudio.lastTime[i] += time;
2134 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2135 mBatteryAudio.lastTime[i] = 0;
2136 } else {
2137 mBatteryAudio.lastTime[i] = 0 - time;
2138 }
2139 }
2140
2141 mBatteryAudio.deviceOn[i] = deviceOn[i];
2142 }
2143 }
2144 return;
2145 }
2146
Marco Nelissenb7848f12014-12-04 08:57:56 -08002147 // an audio stream is started
Gloria Wang9ee159b2011-02-24 14:51:45 -08002148 if (params & kBatteryDataAudioFlingerStart) {
2149 // record the start time only if currently no other audio
2150 // is being played
2151 if (mBatteryAudio.refCount == 0) {
2152 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2153 if (mBatteryAudio.deviceOn[i]) {
2154 mBatteryAudio.lastTime[i] -= time;
2155 }
2156 }
2157 }
2158
2159 mBatteryAudio.refCount ++;
2160 return;
2161
2162 } else if (params & kBatteryDataAudioFlingerStop) {
2163 if (mBatteryAudio.refCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002164 ALOGW("Battery track warning: refCount is <= 0");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002165 return;
2166 }
2167
2168 // record the stop time only if currently this is the only
2169 // audio being played
2170 if (mBatteryAudio.refCount == 1) {
2171 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2172 if (mBatteryAudio.deviceOn[i]) {
2173 mBatteryAudio.lastTime[i] += time;
2174 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2175 mBatteryAudio.lastTime[i] = 0;
2176 }
2177 }
2178 }
2179
2180 mBatteryAudio.refCount --;
2181 return;
2182 }
2183
Gloria Wang7cf180c2011-02-19 18:37:57 -08002184 int uid = IPCThreadState::self()->getCallingUid();
2185 if (uid == AID_MEDIA) {
2186 return;
2187 }
2188 int index = mBatteryData.indexOfKey(uid);
Gloria Wang7cf180c2011-02-19 18:37:57 -08002189
2190 if (index < 0) { // create a new entry for this UID
2191 BatteryUsageInfo info;
2192 info.audioTotalTime = 0;
2193 info.videoTotalTime = 0;
2194 info.audioLastTime = 0;
2195 info.videoLastTime = 0;
2196 info.refCount = 0;
2197
Gloria Wang9ee159b2011-02-24 14:51:45 -08002198 if (mBatteryData.add(uid, info) == NO_MEMORY) {
Steve Block29357bc2012-01-06 19:20:56 +00002199 ALOGE("Battery track error: no memory for new app");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002200 return;
2201 }
Gloria Wang7cf180c2011-02-19 18:37:57 -08002202 }
2203
2204 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
2205
2206 if (params & kBatteryDataCodecStarted) {
2207 if (params & kBatteryDataTrackAudio) {
2208 info.audioLastTime -= time;
2209 info.refCount ++;
2210 }
2211 if (params & kBatteryDataTrackVideo) {
2212 info.videoLastTime -= time;
2213 info.refCount ++;
2214 }
2215 } else {
2216 if (info.refCount == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002217 ALOGW("Battery track warning: refCount is already 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002218 return;
2219 } else if (info.refCount < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00002220 ALOGE("Battery track error: refCount < 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002221 mBatteryData.removeItem(uid);
2222 return;
2223 }
2224
2225 if (params & kBatteryDataTrackAudio) {
2226 info.audioLastTime += time;
2227 info.refCount --;
2228 }
2229 if (params & kBatteryDataTrackVideo) {
2230 info.videoLastTime += time;
2231 info.refCount --;
2232 }
2233
2234 // no stream is being played by this UID
2235 if (info.refCount == 0) {
2236 info.audioTotalTime += info.audioLastTime;
2237 info.audioLastTime = 0;
2238 info.videoTotalTime += info.videoLastTime;
2239 info.videoLastTime = 0;
2240 }
2241 }
2242}
2243
2244status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
2245 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002246
2247 // audio output devices usage
2248 int32_t time = systemTime() / 1000000L; //in ms
2249 int32_t totalTime;
2250
2251 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2252 totalTime = mBatteryAudio.totalTime[i];
2253
2254 if (mBatteryAudio.deviceOn[i]
2255 && (mBatteryAudio.lastTime[i] != 0)) {
2256 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
2257 totalTime += tmpTime;
2258 }
2259
2260 reply->writeInt32(totalTime);
2261 // reset the total time
2262 mBatteryAudio.totalTime[i] = 0;
2263 }
2264
2265 // codec usage
Gloria Wang7cf180c2011-02-19 18:37:57 -08002266 BatteryUsageInfo info;
2267 int size = mBatteryData.size();
2268
2269 reply->writeInt32(size);
2270 int i = 0;
2271
2272 while (i < size) {
2273 info = mBatteryData.valueAt(i);
2274
2275 reply->writeInt32(mBatteryData.keyAt(i)); //UID
2276 reply->writeInt32(info.audioTotalTime);
2277 reply->writeInt32(info.videoTotalTime);
2278
2279 info.audioTotalTime = 0;
2280 info.videoTotalTime = 0;
2281
2282 // remove the UID entry where no stream is being played
2283 if (info.refCount <= 0) {
2284 mBatteryData.removeItemsAt(i);
2285 size --;
2286 i --;
2287 }
2288 i++;
2289 }
2290 return NO_ERROR;
2291}
nikoa64c8c72009-07-20 15:07:26 -07002292} // namespace android