blob: 6339c728cec1df7be89ea60350284e9d14d44942 [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
Wei Jia502c2f42017-07-13 17:47:56 -070087static const int kDumpLockRetries = 50;
88static const int kDumpLockSleepUs = 20000;
89
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070090namespace {
nikoa64c8c72009-07-20 15:07:26 -070091using android::media::Metadata;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070092using android::status_t;
93using android::OK;
94using android::BAD_VALUE;
95using android::NOT_ENOUGH_DATA;
96using android::Parcel;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070097
98// Max number of entries in the filter.
99const int kMaxFilterSize = 64; // I pulled that out of thin air.
100
nikoa64c8c72009-07-20 15:07:26 -0700101// FIXME: Move all the metadata related function in the Metadata.cpp
nikod608a812009-07-16 16:39:53 -0700102
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700103
104// Unmarshall a filter from a Parcel.
105// Filter format in a parcel:
106//
107// 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
108// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
109// | number of entries (n) |
110// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
111// | metadata type 1 |
112// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
113// | metadata type 2 |
114// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
115// ....
116// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
117// | metadata type n |
118// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
119//
120// @param p Parcel that should start with a filter.
121// @param[out] filter On exit contains the list of metadata type to be
122// filtered.
123// @param[out] status On exit contains the status code to be returned.
124// @return true if the parcel starts with a valid filter.
125bool unmarshallFilter(const Parcel& p,
nikoa64c8c72009-07-20 15:07:26 -0700126 Metadata::Filter *filter,
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700127 status_t *status)
128{
Nicolas Catania48290382009-07-10 13:53:06 -0700129 int32_t val;
130 if (p.readInt32(&val) != OK)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700131 {
Steve Block29357bc2012-01-06 19:20:56 +0000132 ALOGE("Failed to read filter's length");
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700133 *status = NOT_ENOUGH_DATA;
134 return false;
135 }
136
Nicolas Catania48290382009-07-10 13:53:06 -0700137 if( val > kMaxFilterSize || val < 0)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700138 {
Steve Block29357bc2012-01-06 19:20:56 +0000139 ALOGE("Invalid filter len %d", val);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700140 *status = BAD_VALUE;
141 return false;
142 }
143
Nicolas Catania48290382009-07-10 13:53:06 -0700144 const size_t num = val;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700145
146 filter->clear();
Nicolas Catania48290382009-07-10 13:53:06 -0700147 filter->setCapacity(num);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700148
nikoa64c8c72009-07-20 15:07:26 -0700149 size_t size = num * sizeof(Metadata::Type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700150
Nicolas Catania48290382009-07-10 13:53:06 -0700151
152 if (p.dataAvail() < size)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700153 {
Steve Block29357bc2012-01-06 19:20:56 +0000154 ALOGE("Filter too short expected %d but got %d", size, p.dataAvail());
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700155 *status = NOT_ENOUGH_DATA;
156 return false;
157 }
158
nikoa64c8c72009-07-20 15:07:26 -0700159 const Metadata::Type *data =
160 static_cast<const Metadata::Type*>(p.readInplace(size));
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700161
Nicolas Catania48290382009-07-10 13:53:06 -0700162 if (NULL == data)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700163 {
Steve Block29357bc2012-01-06 19:20:56 +0000164 ALOGE("Filter had no data");
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700165 *status = BAD_VALUE;
166 return false;
167 }
168
169 // TODO: The stl impl of vector would be more efficient here
170 // because it degenerates into a memcpy on pod types. Try to
171 // replace later or use stl::set.
Nicolas Catania48290382009-07-10 13:53:06 -0700172 for (size_t i = 0; i < num; ++i)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700173 {
Nicolas Catania48290382009-07-10 13:53:06 -0700174 filter->add(*data);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700175 ++data;
176 }
177 *status = OK;
178 return true;
179}
180
Nicolas Catania48290382009-07-10 13:53:06 -0700181// @param filter Of metadata type.
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700182// @param val To be searched.
183// @return true if a match was found.
nikoa64c8c72009-07-20 15:07:26 -0700184bool findMetadata(const Metadata::Filter& filter, const int32_t val)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700185{
186 // Deal with empty and ANY right away
187 if (filter.isEmpty()) return false;
nikoa64c8c72009-07-20 15:07:26 -0700188 if (filter[0] == Metadata::kAny) return true;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700189
Nicolas Catania48290382009-07-10 13:53:06 -0700190 return filter.indexOf(val) >= 0;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700191}
192
193} // anonymous namespace
194
195
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700196namespace {
197using android::Parcel;
198using android::String16;
199
200// marshalling tag indicating flattened utf16 tags
201// keep in sync with frameworks/base/media/java/android/media/AudioAttributes.java
202const int32_t kAudioAttributesMarshallTagFlattenTags = 1;
203
204// Audio attributes format in a parcel:
205//
206// 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
207// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
208// | usage |
209// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
210// | content_type |
211// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Hyejin Kim4f418f92014-09-05 15:50:03 +0900212// | source |
213// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700214// | flags |
215// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
216// | kAudioAttributesMarshallTagFlattenTags | // ignore tags if not found
217// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
218// | flattened tags in UTF16 |
219// | ... |
220// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
221//
222// @param p Parcel that contains audio attributes.
223// @param[out] attributes On exit points to an initialized audio_attributes_t structure
224// @param[out] status On exit contains the status code to be returned.
225void unmarshallAudioAttributes(const Parcel& parcel, audio_attributes_t *attributes)
226{
227 attributes->usage = (audio_usage_t) parcel.readInt32();
228 attributes->content_type = (audio_content_type_t) parcel.readInt32();
Hyejin Kim4f418f92014-09-05 15:50:03 +0900229 attributes->source = (audio_source_t) parcel.readInt32();
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700230 attributes->flags = (audio_flags_mask_t) parcel.readInt32();
231 const bool hasFlattenedTag = (parcel.readInt32() == kAudioAttributesMarshallTagFlattenTags);
232 if (hasFlattenedTag) {
233 // the tags are UTF16, convert to UTF8
234 String16 tags = parcel.readString16();
235 ssize_t realTagSize = utf16_to_utf8_length(tags.string(), tags.size());
236 if (realTagSize <= 0) {
237 strcpy(attributes->tags, "");
238 } else {
239 // copy the flattened string into the attributes as the destination for the conversion:
240 // copying array size -1, array for tags was calloc'd, no need to NULL-terminate it
241 size_t tagSize = realTagSize > AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 ?
242 AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 : realTagSize;
Sergio Giro0c9742d2016-06-28 18:24:52 +0100243 utf16_to_utf8(tags.string(), tagSize, attributes->tags,
244 sizeof(attributes->tags) / sizeof(attributes->tags[0]));
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700245 }
246 } else {
247 ALOGE("unmarshallAudioAttributes() received unflattened tags, ignoring tag values");
248 strcpy(attributes->tags, "");
249 }
250}
251} // anonymous namespace
252
253
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800254namespace android {
255
Marco Nelissenf09611f2015-02-13 14:12:42 -0800256extern ALooperRoster gLooperRoster;
257
258
Dave Burked681bbb2011-08-30 14:39:17 +0100259static bool checkPermission(const char* permissionString) {
260#ifndef HAVE_ANDROID_OS
261 return true;
262#endif
263 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
264 bool ok = checkCallingPermission(String16(permissionString));
Steve Block29357bc2012-01-06 19:20:56 +0000265 if (!ok) ALOGE("Request requires %s", permissionString);
Dave Burked681bbb2011-08-30 14:39:17 +0100266 return ok;
267}
268
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800269// 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 -0800270/* static */ int MediaPlayerService::AudioOutput::mMinBufferCount = 4;
271/* static */ bool MediaPlayerService::AudioOutput::mIsOnEmulator = false;
272
273void MediaPlayerService::instantiate() {
274 defaultServiceManager()->addService(
275 String16("media.player"), new MediaPlayerService());
276}
277
278MediaPlayerService::MediaPlayerService()
279{
Steve Block3856b092011-10-20 11:56:00 +0100280 ALOGV("MediaPlayerService created");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800281 mNextConnId = 1;
Gloria Wang9ee159b2011-02-24 14:51:45 -0800282
283 mBatteryAudio.refCount = 0;
284 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
285 mBatteryAudio.deviceOn[i] = 0;
286 mBatteryAudio.lastTime[i] = 0;
287 mBatteryAudio.totalTime[i] = 0;
288 }
289 // speaker is on by default
290 mBatteryAudio.deviceOn[SPEAKER] = 1;
John Grossman44a7e422012-06-21 17:29:24 -0700291
Chong Zhang0b30fd42014-07-23 14:46:05 -0700292 // reset battery stats
293 // if the mediaserver has crashed, battery stats could be left
294 // in bad state, reset the state upon service start.
Ruben Brunk99e69712015-05-26 17:25:07 -0700295 BatteryNotifier& notifier(BatteryNotifier::getInstance());
296 notifier.noteResetVideo();
297 notifier.noteResetAudio();
Chong Zhang0b30fd42014-07-23 14:46:05 -0700298
John Grossman44a7e422012-06-21 17:29:24 -0700299 MediaPlayerFactory::registerBuiltinFactories();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800300}
301
302MediaPlayerService::~MediaPlayerService()
303{
Steve Block3856b092011-10-20 11:56:00 +0100304 ALOGV("MediaPlayerService destroyed");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800305}
306
Svet Ganovbe71aa22015-04-28 12:06:02 -0700307sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(const String16 &opPackageName)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800308{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800309 pid_t pid = IPCThreadState::self()->getCallingPid();
Svet Ganovbe71aa22015-04-28 12:06:02 -0700310 sp<MediaRecorderClient> recorder = new MediaRecorderClient(this, pid, opPackageName);
Gloria Wangdac6a312009-10-29 15:46:37 -0700311 wp<MediaRecorderClient> w = recorder;
312 Mutex::Autolock lock(mLock);
313 mMediaRecorderClients.add(w);
Steve Block3856b092011-10-20 11:56:00 +0100314 ALOGV("Create new media recorder client from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800315 return recorder;
316}
317
Gloria Wangdac6a312009-10-29 15:46:37 -0700318void MediaPlayerService::removeMediaRecorderClient(wp<MediaRecorderClient> client)
319{
320 Mutex::Autolock lock(mLock);
321 mMediaRecorderClients.remove(client);
Steve Block3856b092011-10-20 11:56:00 +0100322 ALOGV("Delete media recorder client");
Gloria Wangdac6a312009-10-29 15:46:37 -0700323}
324
Glenn Kastenf37971f2012-02-03 11:06:53 -0800325sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800326{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800327 pid_t pid = IPCThreadState::self()->getCallingPid();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800328 sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
Steve Block3856b092011-10-20 11:56:00 +0100329 ALOGV("Create new media retriever from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800330 return retriever;
331}
332
Glenn Kastenf37971f2012-02-03 11:06:53 -0800333sp<IMediaPlayer> MediaPlayerService::create(const sp<IMediaPlayerClient>& client,
Dave Burked681bbb2011-08-30 14:39:17 +0100334 int audioSessionId)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800335{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800336 pid_t pid = IPCThreadState::self()->getCallingPid();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800337 int32_t connId = android_atomic_inc(&mNextConnId);
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700338
339 sp<Client> c = new Client(
340 this, pid, connId, client, audioSessionId,
341 IPCThreadState::self()->getCallingUid());
342
Steve Block3856b092011-10-20 11:56:00 +0100343 ALOGV("Create new client(%d) from pid %d, uid %d, ", connId, pid,
Dave Burked681bbb2011-08-30 14:39:17 +0100344 IPCThreadState::self()->getCallingUid());
345
346 wp<Client> w = c;
347 {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800348 Mutex::Autolock lock(mLock);
349 mClients.add(w);
350 }
Andreas Hubere2b10282010-11-23 11:41:34 -0800351 return c;
352}
353
Lajos Molnar1381d4b2014-08-07 15:18:35 -0700354sp<IMediaCodecList> MediaPlayerService::getCodecList() const {
355 return MediaCodecList::getLocalInstance();
356}
357
Andreas Huber318ad9c2009-10-15 13:46:54 -0700358sp<IOMX> MediaPlayerService::getOMX() {
359 Mutex::Autolock autoLock(mLock);
360
361 if (mOMX.get() == NULL) {
362 mOMX = new OMX;
363 }
364
365 return mOMX;
Andreas Huber20111aa2009-07-14 16:56:47 -0700366}
367
Andreas Hubered3e3e02012-03-26 11:13:27 -0700368sp<ICrypto> MediaPlayerService::makeCrypto() {
Andreas Huber1bd139a2012-04-03 14:19:20 -0700369 return new Crypto;
Andreas Hubered3e3e02012-03-26 11:13:27 -0700370}
371
Jeff Tinkercc82dc62013-02-08 10:18:35 -0800372sp<IDrm> MediaPlayerService::makeDrm() {
373 return new Drm;
374}
375
Andreas Huber279dcd82013-01-30 10:41:25 -0800376sp<IHDCP> MediaPlayerService::makeHDCP(bool createEncryptionModule) {
377 return new HDCP(createEncryptionModule);
Andreas Huber59451f82012-09-18 10:36:32 -0700378}
379
Jeff Brown2013a542012-09-04 21:38:42 -0700380sp<IRemoteDisplay> MediaPlayerService::listenForRemoteDisplay(
Svet Ganovbe71aa22015-04-28 12:06:02 -0700381 const String16 &opPackageName,
Jeff Brown2013a542012-09-04 21:38:42 -0700382 const sp<IRemoteDisplayClient>& client, const String8& iface) {
Jeff Brownaba33d52012-09-07 17:38:58 -0700383 if (!checkPermission("android.permission.CONTROL_WIFI_DISPLAY")) {
384 return NULL;
385 }
386
Svet Ganovbe71aa22015-04-28 12:06:02 -0700387 return new RemoteDisplay(opPackageName, client, iface.string());
Jeff Brown2013a542012-09-04 21:38:42 -0700388}
389
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800390status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
391{
392 const size_t SIZE = 256;
393 char buffer[SIZE];
394 String8 result;
395
396 result.append(" AudioOutput\n");
397 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n",
398 mStreamType, mLeftVolume, mRightVolume);
399 result.append(buffer);
400 snprintf(buffer, 255, " msec per frame(%f), latency (%d)\n",
Eric Laurentdb354e52012-03-05 17:27:11 -0800401 mMsecsPerFrame, (mTrack != 0) ? mTrack->latency() : -1);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800402 result.append(buffer);
Eric Laurent2beeb502010-07-16 07:43:46 -0700403 snprintf(buffer, 255, " aux effect id(%d), send level (%f)\n",
404 mAuxEffectId, mSendLevel);
405 result.append(buffer);
406
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800407 ::write(fd, result.string(), result.size());
408 if (mTrack != 0) {
409 mTrack->dump(fd, args);
410 }
411 return NO_ERROR;
412}
413
Lajos Molnar6d339f12015-04-17 16:15:53 -0700414status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800415{
416 const size_t SIZE = 256;
417 char buffer[SIZE];
418 String8 result;
419 result.append(" Client\n");
420 snprintf(buffer, 255, " pid(%d), connId(%d), status(%d), looping(%s)\n",
421 mPid, mConnId, mStatus, mLoop?"true": "false");
422 result.append(buffer);
Wei Jia502c2f42017-07-13 17:47:56 -0700423
424 sp<MediaPlayerBase> p;
425 sp<AudioOutput> audioOutput;
426 bool locked = false;
427 for (int i = 0; i < kDumpLockRetries; ++i) {
428 if (mLock.tryLock() == NO_ERROR) {
429 locked = true;
430 break;
431 }
432 usleep(kDumpLockSleepUs);
Andreas Hubera0b1d4b2011-06-07 15:52:25 -0700433 }
Wei Jia502c2f42017-07-13 17:47:56 -0700434
435 if (locked) {
436 p = mPlayer;
437 audioOutput = mAudioOutput;
438 mLock.unlock();
439 } else {
440 result.append(" lock is taken, no dump from player and audio output\n");
441 }
442 write(fd, result.string(), result.size());
443
444 if (p != NULL) {
445 p->dump(fd, args);
446 }
447 if (audioOutput != 0) {
448 audioOutput->dump(fd, args);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800449 }
450 write(fd, "\n", 1);
451 return NO_ERROR;
452}
453
Marco Nelissenf09611f2015-02-13 14:12:42 -0800454/**
455 * The only arguments this understands right now are -c, -von and -voff,
456 * which are parsed by ALooperRoster::dump()
457 */
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800458status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
459{
460 const size_t SIZE = 256;
461 char buffer[SIZE];
462 String8 result;
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530463 SortedVector< sp<Client> > clients; //to serialise the mutex unlock & client destruction.
464 SortedVector< sp<MediaRecorderClient> > mediaRecorderClients;
465
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800466 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
467 snprintf(buffer, SIZE, "Permission Denial: "
468 "can't dump MediaPlayerService from pid=%d, uid=%d\n",
469 IPCThreadState::self()->getCallingPid(),
470 IPCThreadState::self()->getCallingUid());
471 result.append(buffer);
472 } else {
473 Mutex::Autolock lock(mLock);
474 for (int i = 0, n = mClients.size(); i < n; ++i) {
475 sp<Client> c = mClients[i].promote();
476 if (c != 0) c->dump(fd, args);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530477 clients.add(c);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800478 }
James Dongb9141222010-07-08 11:16:11 -0700479 if (mMediaRecorderClients.size() == 0) {
480 result.append(" No media recorder client\n\n");
481 } else {
482 for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
483 sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
James Donge579e282011-10-18 22:29:20 -0700484 if (c != 0) {
485 snprintf(buffer, 255, " MediaRecorderClient pid(%d)\n", c->mPid);
486 result.append(buffer);
487 write(fd, result.string(), result.size());
488 result = "\n";
489 c->dump(fd, args);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530490 mediaRecorderClients.add(c);
James Donge579e282011-10-18 22:29:20 -0700491 }
James Dongb9141222010-07-08 11:16:11 -0700492 }
Gloria Wangdac6a312009-10-29 15:46:37 -0700493 }
494
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800495 result.append(" Files opened and/or mapped:\n");
Marco Nelissenf09611f2015-02-13 14:12:42 -0800496 snprintf(buffer, SIZE, "/proc/%d/maps", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800497 FILE *f = fopen(buffer, "r");
498 if (f) {
499 while (!feof(f)) {
500 fgets(buffer, SIZE, f);
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700501 if (strstr(buffer, " /storage/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800502 strstr(buffer, " /system/sounds/") ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700503 strstr(buffer, " /data/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800504 strstr(buffer, " /system/media/")) {
505 result.append(" ");
506 result.append(buffer);
507 }
508 }
509 fclose(f);
510 } else {
511 result.append("couldn't open ");
512 result.append(buffer);
513 result.append("\n");
514 }
515
Marco Nelissenf09611f2015-02-13 14:12:42 -0800516 snprintf(buffer, SIZE, "/proc/%d/fd", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800517 DIR *d = opendir(buffer);
518 if (d) {
519 struct dirent *ent;
520 while((ent = readdir(d)) != NULL) {
521 if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
Marco Nelissenf09611f2015-02-13 14:12:42 -0800522 snprintf(buffer, SIZE, "/proc/%d/fd/%s", getpid(), ent->d_name);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800523 struct stat s;
524 if (lstat(buffer, &s) == 0) {
525 if ((s.st_mode & S_IFMT) == S_IFLNK) {
526 char linkto[256];
527 int len = readlink(buffer, linkto, sizeof(linkto));
528 if(len > 0) {
529 if(len > 255) {
530 linkto[252] = '.';
531 linkto[253] = '.';
532 linkto[254] = '.';
533 linkto[255] = 0;
534 } else {
535 linkto[len] = 0;
536 }
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700537 if (strstr(linkto, "/storage/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800538 strstr(linkto, "/system/sounds/") == linkto ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700539 strstr(linkto, "/data/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800540 strstr(linkto, "/system/media/") == linkto) {
541 result.append(" ");
542 result.append(buffer);
543 result.append(" -> ");
544 result.append(linkto);
545 result.append("\n");
546 }
547 }
548 } else {
549 result.append(" unexpected type for ");
550 result.append(buffer);
551 result.append("\n");
552 }
553 }
554 }
555 }
556 closedir(d);
557 } else {
558 result.append("couldn't open ");
559 result.append(buffer);
560 result.append("\n");
561 }
562
Marco Nelissenf09611f2015-02-13 14:12:42 -0800563 gLooperRoster.dump(fd, args);
564
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800565 bool dumpMem = false;
566 for (size_t i = 0; i < args.size(); i++) {
567 if (args[i] == String16("-m")) {
568 dumpMem = true;
569 }
570 }
571 if (dumpMem) {
James Dong8635b7b2011-03-14 17:01:38 -0700572 dumpMemoryAddresses(fd);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800573 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800574 }
575 write(fd, result.string(), result.size());
576 return NO_ERROR;
577}
578
579void MediaPlayerService::removeClient(wp<Client> client)
580{
581 Mutex::Autolock lock(mLock);
582 mClients.remove(client);
583}
584
Robert Shihee0a0e32016-08-16 16:50:54 -0700585bool MediaPlayerService::hasClient(wp<Client> client)
586{
587 Mutex::Autolock lock(mLock);
588 return mClients.indexOf(client) != NAME_NOT_FOUND;
589}
590
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700591MediaPlayerService::Client::Client(
592 const sp<MediaPlayerService>& service, pid_t pid,
593 int32_t connId, const sp<IMediaPlayerClient>& client,
594 int audioSessionId, uid_t uid)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800595{
Steve Block3856b092011-10-20 11:56:00 +0100596 ALOGV("Client(%d) constructor", connId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800597 mPid = pid;
598 mConnId = connId;
599 mService = service;
600 mClient = client;
601 mLoop = false;
602 mStatus = NO_INIT;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700603 mAudioSessionId = audioSessionId;
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700604 mUID = uid;
John Grossmanc795b642012-02-22 15:38:35 -0800605 mRetransmitEndpointValid = false;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700606 mAudioAttributes = NULL;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700607
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800608#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000609 ALOGD("create Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800610 mAntagonizer = new Antagonizer(notify, this);
611#endif
612}
613
614MediaPlayerService::Client::~Client()
615{
Steve Block3856b092011-10-20 11:56:00 +0100616 ALOGV("Client(%d) destructor pid = %d", mConnId, mPid);
Wei Jia502c2f42017-07-13 17:47:56 -0700617 {
618 Mutex::Autolock l(mLock);
619 mAudioOutput.clear();
620 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800621 wp<Client> client(this);
622 disconnect();
623 mService->removeClient(client);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700624 if (mAudioAttributes != NULL) {
625 free(mAudioAttributes);
626 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800627}
628
629void MediaPlayerService::Client::disconnect()
630{
Steve Block3856b092011-10-20 11:56:00 +0100631 ALOGV("disconnect(%d) from pid %d", mConnId, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800632 // grab local reference and clear main reference to prevent future
633 // access to object
634 sp<MediaPlayerBase> p;
635 {
636 Mutex::Autolock l(mLock);
637 p = mPlayer;
beanzdcfefde2012-11-05 09:51:43 +0800638 mClient.clear();
Wei Jia502c2f42017-07-13 17:47:56 -0700639 mPlayer.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800640 }
Andreas Huber20111aa2009-07-14 16:56:47 -0700641
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800642 // clear the notification to prevent callbacks to dead client
643 // and reset the player. We assume the player will serialize
644 // access to itself if necessary.
645 if (p != 0) {
646 p->setNotifyCallback(0, 0);
647#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000648 ALOGD("kill Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800649 mAntagonizer->kill();
650#endif
651 p->reset();
652 }
653
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700654 disconnectNativeWindow();
655
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800656 IPCThreadState::self()->flushCommands();
657}
658
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800659sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
660{
661 // determine if we have the right player type
Wei Jia502c2f42017-07-13 17:47:56 -0700662 sp<MediaPlayerBase> p = getPlayer();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800663 if ((p != NULL) && (p->playerType() != playerType)) {
Steve Block3856b092011-10-20 11:56:00 +0100664 ALOGV("delete player");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800665 p.clear();
666 }
667 if (p == NULL) {
Ronghua Wu68845c12015-07-21 09:50:48 -0700668 p = MediaPlayerFactory::createPlayer(playerType, this, notify, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800669 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700670
Jason Simmonsdb29e522011-08-12 13:46:55 -0700671 if (p != NULL) {
672 p->setUID(mUID);
673 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700674
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800675 return p;
676}
677
John Grossmanc795b642012-02-22 15:38:35 -0800678sp<MediaPlayerBase> MediaPlayerService::Client::setDataSource_pre(
679 player_type playerType)
680{
681 ALOGV("player type = %d", playerType);
682
683 // create the right type of player
684 sp<MediaPlayerBase> p = createPlayer(playerType);
685 if (p == NULL) {
686 return p;
687 }
688
689 if (!p->hardwareOutput()) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -0700690 Mutex::Autolock l(mLock);
Marco Nelissend457c972014-02-11 08:47:07 -0800691 mAudioOutput = new AudioOutput(mAudioSessionId, IPCThreadState::self()->getCallingUid(),
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700692 mPid, mAudioAttributes);
John Grossmanc795b642012-02-22 15:38:35 -0800693 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
694 }
695
696 return p;
697}
698
699void MediaPlayerService::Client::setDataSource_post(
700 const sp<MediaPlayerBase>& p,
701 status_t status)
702{
703 ALOGV(" setDataSource");
704 mStatus = status;
705 if (mStatus != OK) {
706 ALOGE(" error: %d", mStatus);
707 return;
708 }
709
710 // Set the re-transmission endpoint if one was chosen.
711 if (mRetransmitEndpointValid) {
712 mStatus = p->setRetransmitEndpoint(&mRetransmitEndpoint);
713 if (mStatus != NO_ERROR) {
714 ALOGE("setRetransmitEndpoint error: %d", mStatus);
715 }
716 }
717
718 if (mStatus == OK) {
Wei Jia502c2f42017-07-13 17:47:56 -0700719 Mutex::Autolock l(mLock);
John Grossmanc795b642012-02-22 15:38:35 -0800720 mPlayer = p;
721 }
722}
723
Andreas Huber2db84552010-01-28 11:19:57 -0800724status_t MediaPlayerService::Client::setDataSource(
Andreas Huber1b86fe02014-01-29 11:13:26 -0800725 const sp<IMediaHTTPService> &httpService,
726 const char *url,
727 const KeyedVector<String8, String8> *headers)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800728{
Steve Block3856b092011-10-20 11:56:00 +0100729 ALOGV("setDataSource(%s)", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800730 if (url == NULL)
731 return UNKNOWN_ERROR;
732
Dave Burked681bbb2011-08-30 14:39:17 +0100733 if ((strncmp(url, "http://", 7) == 0) ||
734 (strncmp(url, "https://", 8) == 0) ||
735 (strncmp(url, "rtsp://", 7) == 0)) {
736 if (!checkPermission("android.permission.INTERNET")) {
737 return PERMISSION_DENIED;
738 }
739 }
740
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800741 if (strncmp(url, "content://", 10) == 0) {
742 // get a filedescriptor for the content Uri and
743 // pass it to the setDataSource(fd) method
744
745 String16 url16(url);
746 int fd = android::openContentProviderFile(url16);
747 if (fd < 0)
748 {
Steve Block29357bc2012-01-06 19:20:56 +0000749 ALOGE("Couldn't open fd for %s", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800750 return UNKNOWN_ERROR;
751 }
752 setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
753 close(fd);
754 return mStatus;
755 } else {
John Grossman44a7e422012-06-21 17:29:24 -0700756 player_type playerType = MediaPlayerFactory::getPlayerType(this, url);
John Grossmanc795b642012-02-22 15:38:35 -0800757 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
758 if (p == NULL) {
759 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800760 }
761
Andreas Huber1b86fe02014-01-29 11:13:26 -0800762 setDataSource_post(p, p->setDataSource(httpService, url, headers));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800763 return mStatus;
764 }
765}
766
767status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
768{
Steve Block3856b092011-10-20 11:56:00 +0100769 ALOGV("setDataSource fd=%d, offset=%lld, length=%lld", fd, offset, length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800770 struct stat sb;
771 int ret = fstat(fd, &sb);
772 if (ret != 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000773 ALOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800774 return UNKNOWN_ERROR;
775 }
776
Ying Wang5fde15d2015-04-20 22:13:22 -0700777 ALOGV("st_dev = %llu", static_cast<uint64_t>(sb.st_dev));
Steve Block3856b092011-10-20 11:56:00 +0100778 ALOGV("st_mode = %u", sb.st_mode);
Mark Salyzyn77342f72014-06-18 16:31:32 -0700779 ALOGV("st_uid = %lu", static_cast<unsigned long>(sb.st_uid));
780 ALOGV("st_gid = %lu", static_cast<unsigned long>(sb.st_gid));
Steve Block3856b092011-10-20 11:56:00 +0100781 ALOGV("st_size = %llu", sb.st_size);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800782
783 if (offset >= sb.st_size) {
Steve Block29357bc2012-01-06 19:20:56 +0000784 ALOGE("offset error");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800785 ::close(fd);
786 return UNKNOWN_ERROR;
787 }
788 if (offset + length > sb.st_size) {
789 length = sb.st_size - offset;
Steve Block3856b092011-10-20 11:56:00 +0100790 ALOGV("calculated length = %lld", length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800791 }
792
John Grossman44a7e422012-06-21 17:29:24 -0700793 player_type playerType = MediaPlayerFactory::getPlayerType(this,
794 fd,
795 offset,
796 length);
John Grossmanc795b642012-02-22 15:38:35 -0800797 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
798 if (p == NULL) {
799 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800800 }
801
802 // now set data source
John Grossmanc795b642012-02-22 15:38:35 -0800803 setDataSource_post(p, p->setDataSource(fd, offset, length));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800804 return mStatus;
805}
806
Andreas Hubere2b10282010-11-23 11:41:34 -0800807status_t MediaPlayerService::Client::setDataSource(
808 const sp<IStreamSource> &source) {
809 // create the right type of player
John Grossman44a7e422012-06-21 17:29:24 -0700810 player_type playerType = MediaPlayerFactory::getPlayerType(this, source);
John Grossmanc795b642012-02-22 15:38:35 -0800811 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
Andreas Hubere2b10282010-11-23 11:41:34 -0800812 if (p == NULL) {
813 return NO_INIT;
814 }
815
Andreas Hubere2b10282010-11-23 11:41:34 -0800816 // now set data source
John Grossmanc795b642012-02-22 15:38:35 -0800817 setDataSource_post(p, p->setDataSource(source));
Andreas Hubere2b10282010-11-23 11:41:34 -0800818 return mStatus;
819}
820
Chris Watkins99f31602015-03-20 13:06:33 -0700821status_t MediaPlayerService::Client::setDataSource(
822 const sp<IDataSource> &source) {
823 sp<DataSource> dataSource = DataSource::CreateFromIDataSource(source);
824 player_type playerType = MediaPlayerFactory::getPlayerType(this, dataSource);
825 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
826 if (p == NULL) {
827 return NO_INIT;
828 }
829 // now set data source
830 setDataSource_post(p, p->setDataSource(dataSource));
831 return mStatus;
832}
833
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700834void MediaPlayerService::Client::disconnectNativeWindow() {
835 if (mConnectedWindow != NULL) {
836 status_t err = native_window_api_disconnect(mConnectedWindow.get(),
837 NATIVE_WINDOW_API_MEDIA);
838
839 if (err != OK) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000840 ALOGW("native_window_api_disconnect returned an error: %s (%d)",
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700841 strerror(-err), err);
842 }
843 }
844 mConnectedWindow.clear();
845}
846
Glenn Kasten11731182011-02-08 17:26:17 -0800847status_t MediaPlayerService::Client::setVideoSurfaceTexture(
Andy McFadden484566c2012-12-18 09:46:54 -0800848 const sp<IGraphicBufferProducer>& bufferProducer)
Glenn Kasten11731182011-02-08 17:26:17 -0800849{
Andy McFadden484566c2012-12-18 09:46:54 -0800850 ALOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, bufferProducer.get());
Glenn Kasten11731182011-02-08 17:26:17 -0800851 sp<MediaPlayerBase> p = getPlayer();
852 if (p == 0) return UNKNOWN_ERROR;
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700853
Marco Nelissenf8880202014-11-14 07:58:25 -0800854 sp<IBinder> binder(IInterface::asBinder(bufferProducer));
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700855 if (mConnectedWindowBinder == binder) {
856 return OK;
857 }
858
859 sp<ANativeWindow> anw;
Andy McFadden484566c2012-12-18 09:46:54 -0800860 if (bufferProducer != NULL) {
Marco Nelissenee08f7e2013-09-16 13:30:01 -0700861 anw = new Surface(bufferProducer, true /* controlledByApp */);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700862 status_t err = native_window_api_connect(anw.get(),
863 NATIVE_WINDOW_API_MEDIA);
864
865 if (err != OK) {
Steve Block29357bc2012-01-06 19:20:56 +0000866 ALOGE("setVideoSurfaceTexture failed: %d", err);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700867 // Note that we must do the reset before disconnecting from the ANW.
868 // Otherwise queue/dequeue calls could be made on the disconnected
869 // ANW, which may result in errors.
870 reset();
871
872 disconnectNativeWindow();
873
874 return err;
875 }
876 }
877
Andy McFadden484566c2012-12-18 09:46:54 -0800878 // Note that we must set the player's new GraphicBufferProducer before
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700879 // disconnecting the old one. Otherwise queue/dequeue calls could be made
880 // on the disconnected ANW, which may result in errors.
Andy McFadden484566c2012-12-18 09:46:54 -0800881 status_t err = p->setVideoSurfaceTexture(bufferProducer);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700882
883 disconnectNativeWindow();
884
885 mConnectedWindow = anw;
886
887 if (err == OK) {
888 mConnectedWindowBinder = binder;
889 } else {
890 disconnectNativeWindow();
891 }
892
893 return err;
Glenn Kasten11731182011-02-08 17:26:17 -0800894}
895
Nicolas Catania1d187f12009-05-12 23:25:55 -0700896status_t MediaPlayerService::Client::invoke(const Parcel& request,
897 Parcel *reply)
898{
899 sp<MediaPlayerBase> p = getPlayer();
900 if (p == NULL) return UNKNOWN_ERROR;
901 return p->invoke(request, reply);
902}
903
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700904// This call doesn't need to access the native player.
905status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
906{
907 status_t status;
nikoa64c8c72009-07-20 15:07:26 -0700908 media::Metadata::Filter allow, drop;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700909
Nicolas Catania48290382009-07-10 13:53:06 -0700910 if (unmarshallFilter(filter, &allow, &status) &&
911 unmarshallFilter(filter, &drop, &status)) {
912 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700913
914 mMetadataAllow = allow;
915 mMetadataDrop = drop;
916 }
917 return status;
918}
919
Nicolas Catania48290382009-07-10 13:53:06 -0700920status_t MediaPlayerService::Client::getMetadata(
Mark Salyzyn77342f72014-06-18 16:31:32 -0700921 bool update_only, bool /*apply_filter*/, Parcel *reply)
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700922{
nikoa64c8c72009-07-20 15:07:26 -0700923 sp<MediaPlayerBase> player = getPlayer();
924 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania48290382009-07-10 13:53:06 -0700925
nikod608a812009-07-16 16:39:53 -0700926 status_t status;
927 // Placeholder for the return code, updated by the caller.
928 reply->writeInt32(-1);
929
nikoa64c8c72009-07-20 15:07:26 -0700930 media::Metadata::Filter ids;
Nicolas Catania48290382009-07-10 13:53:06 -0700931
932 // We don't block notifications while we fetch the data. We clear
933 // mMetadataUpdated first so we don't lose notifications happening
934 // during the rest of this call.
935 {
936 Mutex::Autolock lock(mLock);
937 if (update_only) {
nikod608a812009-07-16 16:39:53 -0700938 ids = mMetadataUpdated;
Nicolas Catania48290382009-07-10 13:53:06 -0700939 }
940 mMetadataUpdated.clear();
941 }
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700942
nikoa64c8c72009-07-20 15:07:26 -0700943 media::Metadata metadata(reply);
Nicolas Catania48290382009-07-10 13:53:06 -0700944
nikoa64c8c72009-07-20 15:07:26 -0700945 metadata.appendHeader();
946 status = player->getMetadata(ids, reply);
nikod608a812009-07-16 16:39:53 -0700947
948 if (status != OK) {
nikoa64c8c72009-07-20 15:07:26 -0700949 metadata.resetParcel();
Steve Block29357bc2012-01-06 19:20:56 +0000950 ALOGE("getMetadata failed %d", status);
nikod608a812009-07-16 16:39:53 -0700951 return status;
952 }
953
954 // FIXME: Implement filtering on the result. Not critical since
955 // filtering takes place on the update notifications already. This
956 // would be when all the metadata are fetch and a filter is set.
957
nikod608a812009-07-16 16:39:53 -0700958 // Everything is fine, update the metadata length.
nikoa64c8c72009-07-20 15:07:26 -0700959 metadata.updateLength();
nikod608a812009-07-16 16:39:53 -0700960 return OK;
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700961}
962
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800963status_t MediaPlayerService::Client::prepareAsync()
964{
Steve Block3856b092011-10-20 11:56:00 +0100965 ALOGV("[%d] prepareAsync", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800966 sp<MediaPlayerBase> p = getPlayer();
967 if (p == 0) return UNKNOWN_ERROR;
968 status_t ret = p->prepareAsync();
969#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000970 ALOGD("start Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800971 if (ret == NO_ERROR) mAntagonizer->start();
972#endif
973 return ret;
974}
975
976status_t MediaPlayerService::Client::start()
977{
Steve Block3856b092011-10-20 11:56:00 +0100978 ALOGV("[%d] start", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800979 sp<MediaPlayerBase> p = getPlayer();
980 if (p == 0) return UNKNOWN_ERROR;
981 p->setLooping(mLoop);
982 return p->start();
983}
984
985status_t MediaPlayerService::Client::stop()
986{
Steve Block3856b092011-10-20 11:56:00 +0100987 ALOGV("[%d] stop", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800988 sp<MediaPlayerBase> p = getPlayer();
989 if (p == 0) return UNKNOWN_ERROR;
990 return p->stop();
991}
992
993status_t MediaPlayerService::Client::pause()
994{
Steve Block3856b092011-10-20 11:56:00 +0100995 ALOGV("[%d] pause", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800996 sp<MediaPlayerBase> p = getPlayer();
997 if (p == 0) return UNKNOWN_ERROR;
998 return p->pause();
999}
1000
1001status_t MediaPlayerService::Client::isPlaying(bool* state)
1002{
1003 *state = false;
1004 sp<MediaPlayerBase> p = getPlayer();
1005 if (p == 0) return UNKNOWN_ERROR;
1006 *state = p->isPlaying();
Steve Block3856b092011-10-20 11:56:00 +01001007 ALOGV("[%d] isPlaying: %d", mConnId, *state);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001008 return NO_ERROR;
1009}
1010
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001011status_t MediaPlayerService::Client::setPlaybackSettings(const AudioPlaybackRate& rate)
Wei Jia98160162015-02-04 17:01:11 -08001012{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001013 ALOGV("[%d] setPlaybackSettings(%f, %f, %d, %d)",
1014 mConnId, rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Wei Jia98160162015-02-04 17:01:11 -08001015 sp<MediaPlayerBase> p = getPlayer();
1016 if (p == 0) return UNKNOWN_ERROR;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001017 return p->setPlaybackSettings(rate);
1018}
1019
1020status_t MediaPlayerService::Client::getPlaybackSettings(AudioPlaybackRate* rate /* nonnull */)
1021{
1022 sp<MediaPlayerBase> p = getPlayer();
1023 if (p == 0) return UNKNOWN_ERROR;
1024 status_t ret = p->getPlaybackSettings(rate);
1025 if (ret == NO_ERROR) {
1026 ALOGV("[%d] getPlaybackSettings(%f, %f, %d, %d)",
1027 mConnId, rate->mSpeed, rate->mPitch, rate->mFallbackMode, rate->mStretchMode);
1028 } else {
1029 ALOGV("[%d] getPlaybackSettings returned %d", mConnId, ret);
1030 }
1031 return ret;
1032}
1033
1034status_t MediaPlayerService::Client::setSyncSettings(
1035 const AVSyncSettings& sync, float videoFpsHint)
1036{
1037 ALOGV("[%d] setSyncSettings(%u, %u, %f, %f)",
1038 mConnId, sync.mSource, sync.mAudioAdjustMode, sync.mTolerance, videoFpsHint);
1039 sp<MediaPlayerBase> p = getPlayer();
1040 if (p == 0) return UNKNOWN_ERROR;
1041 return p->setSyncSettings(sync, videoFpsHint);
1042}
1043
1044status_t MediaPlayerService::Client::getSyncSettings(
1045 AVSyncSettings* sync /* nonnull */, float* videoFps /* nonnull */)
1046{
1047 sp<MediaPlayerBase> p = getPlayer();
1048 if (p == 0) return UNKNOWN_ERROR;
1049 status_t ret = p->getSyncSettings(sync, videoFps);
1050 if (ret == NO_ERROR) {
1051 ALOGV("[%d] getSyncSettings(%u, %u, %f, %f)",
1052 mConnId, sync->mSource, sync->mAudioAdjustMode, sync->mTolerance, *videoFps);
1053 } else {
1054 ALOGV("[%d] getSyncSettings returned %d", mConnId, ret);
1055 }
1056 return ret;
Wei Jia98160162015-02-04 17:01:11 -08001057}
1058
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001059status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
1060{
Steve Block3856b092011-10-20 11:56:00 +01001061 ALOGV("getCurrentPosition");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001062 sp<MediaPlayerBase> p = getPlayer();
1063 if (p == 0) return UNKNOWN_ERROR;
1064 status_t ret = p->getCurrentPosition(msec);
1065 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001066 ALOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001067 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001068 ALOGE("getCurrentPosition returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001069 }
1070 return ret;
1071}
1072
1073status_t MediaPlayerService::Client::getDuration(int *msec)
1074{
Steve Block3856b092011-10-20 11:56:00 +01001075 ALOGV("getDuration");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001076 sp<MediaPlayerBase> p = getPlayer();
1077 if (p == 0) return UNKNOWN_ERROR;
1078 status_t ret = p->getDuration(msec);
1079 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001080 ALOGV("[%d] getDuration = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001081 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001082 ALOGE("getDuration returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001083 }
1084 return ret;
1085}
1086
Marco Nelissen6b74d672012-02-28 16:07:44 -08001087status_t MediaPlayerService::Client::setNextPlayer(const sp<IMediaPlayer>& player) {
1088 ALOGV("setNextPlayer");
1089 Mutex::Autolock l(mLock);
1090 sp<Client> c = static_cast<Client*>(player.get());
Wei Jia28284122016-08-30 13:49:06 -07001091 if (c != NULL && !mService->hasClient(c)) {
Robert Shihee0a0e32016-08-16 16:50:54 -07001092 return BAD_VALUE;
1093 }
1094
Marco Nelissen6b74d672012-02-28 16:07:44 -08001095 mNextClient = c;
John Grossman5f7e55e2012-08-24 14:47:25 -07001096
1097 if (c != NULL) {
1098 if (mAudioOutput != NULL) {
1099 mAudioOutput->setNextOutput(c->mAudioOutput);
1100 } else if ((mPlayer != NULL) && !mPlayer->hardwareOutput()) {
1101 ALOGE("no current audio output");
1102 }
1103
1104 if ((mPlayer != NULL) && (mNextClient->getPlayer() != NULL)) {
1105 mPlayer->setNextPlayer(mNextClient->getPlayer());
1106 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001107 }
John Grossman5f7e55e2012-08-24 14:47:25 -07001108
Marco Nelissen6b74d672012-02-28 16:07:44 -08001109 return OK;
1110}
1111
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001112status_t MediaPlayerService::Client::seekTo(int msec)
1113{
Steve Block3856b092011-10-20 11:56:00 +01001114 ALOGV("[%d] seekTo(%d)", mConnId, msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001115 sp<MediaPlayerBase> p = getPlayer();
1116 if (p == 0) return UNKNOWN_ERROR;
1117 return p->seekTo(msec);
1118}
1119
1120status_t MediaPlayerService::Client::reset()
1121{
Steve Block3856b092011-10-20 11:56:00 +01001122 ALOGV("[%d] reset", mConnId);
John Grossmanc795b642012-02-22 15:38:35 -08001123 mRetransmitEndpointValid = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001124 sp<MediaPlayerBase> p = getPlayer();
1125 if (p == 0) return UNKNOWN_ERROR;
1126 return p->reset();
1127}
1128
Glenn Kastenfff6d712012-01-12 16:38:12 -08001129status_t MediaPlayerService::Client::setAudioStreamType(audio_stream_type_t type)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001130{
Steve Block3856b092011-10-20 11:56:00 +01001131 ALOGV("[%d] setAudioStreamType(%d)", mConnId, type);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001132 // TODO: for hardware output, call player instead
1133 Mutex::Autolock l(mLock);
1134 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1135 return NO_ERROR;
1136}
1137
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001138status_t MediaPlayerService::Client::setAudioAttributes_l(const Parcel &parcel)
1139{
1140 if (mAudioAttributes != NULL) { free(mAudioAttributes); }
1141 mAudioAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001142 if (mAudioAttributes == NULL) {
1143 return NO_MEMORY;
1144 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001145 unmarshallAudioAttributes(parcel, mAudioAttributes);
1146
1147 ALOGV("setAudioAttributes_l() usage=%d content=%d flags=0x%x tags=%s",
1148 mAudioAttributes->usage, mAudioAttributes->content_type, mAudioAttributes->flags,
1149 mAudioAttributes->tags);
1150
1151 if (mAudioOutput != 0) {
1152 mAudioOutput->setAudioAttributes(mAudioAttributes);
1153 }
1154 return NO_ERROR;
1155}
1156
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001157status_t MediaPlayerService::Client::setLooping(int loop)
1158{
Steve Block3856b092011-10-20 11:56:00 +01001159 ALOGV("[%d] setLooping(%d)", mConnId, loop);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001160 mLoop = loop;
1161 sp<MediaPlayerBase> p = getPlayer();
1162 if (p != 0) return p->setLooping(loop);
1163 return NO_ERROR;
1164}
1165
1166status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1167{
Steve Block3856b092011-10-20 11:56:00 +01001168 ALOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
John Grossman761defc2012-02-09 15:09:05 -08001169
1170 // for hardware output, call player instead
1171 sp<MediaPlayerBase> p = getPlayer();
1172 {
1173 Mutex::Autolock l(mLock);
1174 if (p != 0 && p->hardwareOutput()) {
1175 MediaPlayerHWInterface* hwp =
1176 reinterpret_cast<MediaPlayerHWInterface*>(p.get());
1177 return hwp->setVolume(leftVolume, rightVolume);
1178 } else {
1179 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1180 return NO_ERROR;
1181 }
1182 }
1183
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001184 return NO_ERROR;
1185}
1186
Eric Laurent2beeb502010-07-16 07:43:46 -07001187status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1188{
Steve Block3856b092011-10-20 11:56:00 +01001189 ALOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
Eric Laurent2beeb502010-07-16 07:43:46 -07001190 Mutex::Autolock l(mLock);
1191 if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1192 return NO_ERROR;
1193}
1194
1195status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1196{
Steve Block3856b092011-10-20 11:56:00 +01001197 ALOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
Eric Laurent2beeb502010-07-16 07:43:46 -07001198 Mutex::Autolock l(mLock);
1199 if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1200 return NO_ERROR;
1201}
Nicolas Catania48290382009-07-10 13:53:06 -07001202
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001203status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
Steve Block3856b092011-10-20 11:56:00 +01001204 ALOGV("[%d] setParameter(%d)", mConnId, key);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001205 switch (key) {
1206 case KEY_PARAMETER_AUDIO_ATTRIBUTES:
1207 {
1208 Mutex::Autolock l(mLock);
1209 return setAudioAttributes_l(request);
1210 }
1211 default:
1212 sp<MediaPlayerBase> p = getPlayer();
1213 if (p == 0) { return UNKNOWN_ERROR; }
1214 return p->setParameter(key, request);
1215 }
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001216}
1217
1218status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
Steve Block3856b092011-10-20 11:56:00 +01001219 ALOGV("[%d] getParameter(%d)", mConnId, key);
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001220 sp<MediaPlayerBase> p = getPlayer();
1221 if (p == 0) return UNKNOWN_ERROR;
1222 return p->getParameter(key, reply);
1223}
1224
John Grossmanc795b642012-02-22 15:38:35 -08001225status_t MediaPlayerService::Client::setRetransmitEndpoint(
1226 const struct sockaddr_in* endpoint) {
1227
1228 if (NULL != endpoint) {
1229 uint32_t a = ntohl(endpoint->sin_addr.s_addr);
1230 uint16_t p = ntohs(endpoint->sin_port);
1231 ALOGV("[%d] setRetransmitEndpoint(%u.%u.%u.%u:%hu)", mConnId,
1232 (a >> 24), (a >> 16) & 0xFF, (a >> 8) & 0xFF, (a & 0xFF), p);
1233 } else {
1234 ALOGV("[%d] setRetransmitEndpoint = <none>", mConnId);
1235 }
1236
1237 sp<MediaPlayerBase> p = getPlayer();
1238
1239 // Right now, the only valid time to set a retransmit endpoint is before
1240 // player selection has been made (since the presence or absence of a
1241 // retransmit endpoint is going to determine which player is selected during
1242 // setDataSource).
1243 if (p != 0) return INVALID_OPERATION;
1244
1245 if (NULL != endpoint) {
1246 mRetransmitEndpoint = *endpoint;
1247 mRetransmitEndpointValid = true;
1248 } else {
1249 mRetransmitEndpointValid = false;
1250 }
1251
1252 return NO_ERROR;
1253}
1254
John Grossman44a7e422012-06-21 17:29:24 -07001255status_t MediaPlayerService::Client::getRetransmitEndpoint(
1256 struct sockaddr_in* endpoint)
1257{
1258 if (NULL == endpoint)
1259 return BAD_VALUE;
1260
1261 sp<MediaPlayerBase> p = getPlayer();
1262
1263 if (p != NULL)
1264 return p->getRetransmitEndpoint(endpoint);
1265
1266 if (!mRetransmitEndpointValid)
1267 return NO_INIT;
1268
1269 *endpoint = mRetransmitEndpoint;
1270
1271 return NO_ERROR;
1272}
1273
Gloria Wangb483c472011-04-11 17:23:27 -07001274void MediaPlayerService::Client::notify(
1275 void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001276{
1277 Client* client = static_cast<Client*>(cookie);
James Dongb8a98252012-08-26 16:13:03 -07001278 if (client == NULL) {
1279 return;
1280 }
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001281
James Dongb8a98252012-08-26 16:13:03 -07001282 sp<IMediaPlayerClient> c;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001283 {
1284 Mutex::Autolock l(client->mLock);
James Dongb8a98252012-08-26 16:13:03 -07001285 c = client->mClient;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001286 if (msg == MEDIA_PLAYBACK_COMPLETE && client->mNextClient != NULL) {
John Grossmancb0b7552012-08-23 17:47:31 -07001287 if (client->mAudioOutput != NULL)
1288 client->mAudioOutput->switchToNextOutput();
Marco Nelissen6b74d672012-02-28 16:07:44 -08001289 client->mNextClient->start();
1290 client->mNextClient->mClient->notify(MEDIA_INFO, MEDIA_INFO_STARTED_AS_NEXT, 0, obj);
1291 }
1292 }
1293
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001294 if (MEDIA_INFO == msg &&
Nicolas Catania48290382009-07-10 13:53:06 -07001295 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikoa64c8c72009-07-20 15:07:26 -07001296 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania48290382009-07-10 13:53:06 -07001297
1298 if(client->shouldDropMetadata(metadata_type)) {
1299 return;
1300 }
1301
1302 // Update the list of metadata that have changed. getMetadata
1303 // also access mMetadataUpdated and clears it.
1304 client->addNewMetadataUpdate(metadata_type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001305 }
James Dongb8a98252012-08-26 16:13:03 -07001306
1307 if (c != NULL) {
1308 ALOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
1309 c->notify(msg, ext1, ext2, obj);
1310 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001311}
1312
Nicolas Catania48290382009-07-10 13:53:06 -07001313
nikoa64c8c72009-07-20 15:07:26 -07001314bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001315{
Nicolas Catania48290382009-07-10 13:53:06 -07001316 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001317
Nicolas Catania48290382009-07-10 13:53:06 -07001318 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001319 return true;
1320 }
1321
Nicolas Catania48290382009-07-10 13:53:06 -07001322 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001323 return false;
Nicolas Catania48290382009-07-10 13:53:06 -07001324 } else {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001325 return true;
1326 }
1327}
1328
Nicolas Catania48290382009-07-10 13:53:06 -07001329
nikoa64c8c72009-07-20 15:07:26 -07001330void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania48290382009-07-10 13:53:06 -07001331 Mutex::Autolock lock(mLock);
1332 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1333 mMetadataUpdated.add(metadata_type);
1334 }
1335}
1336
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001337#if CALLBACK_ANTAGONIZER
1338const int Antagonizer::interval = 10000; // 10 msecs
1339
1340Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1341 mExit(false), mActive(false), mClient(client), mCb(cb)
1342{
1343 createThread(callbackThread, this);
1344}
1345
1346void Antagonizer::kill()
1347{
1348 Mutex::Autolock _l(mLock);
1349 mActive = false;
1350 mExit = true;
1351 mCondition.wait(mLock);
1352}
1353
1354int Antagonizer::callbackThread(void* user)
1355{
Steve Blockb8a80522011-12-20 16:23:08 +00001356 ALOGD("Antagonizer started");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001357 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1358 while (!p->mExit) {
1359 if (p->mActive) {
Steve Block3856b092011-10-20 11:56:00 +01001360 ALOGV("send event");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001361 p->mCb(p->mClient, 0, 0, 0);
1362 }
1363 usleep(interval);
1364 }
1365 Mutex::Autolock _l(p->mLock);
1366 p->mCondition.signal();
Steve Blockb8a80522011-12-20 16:23:08 +00001367 ALOGD("Antagonizer stopped");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001368 return 0;
1369}
1370#endif
1371
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001372#undef LOG_TAG
1373#define LOG_TAG "AudioSink"
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001374MediaPlayerService::AudioOutput::AudioOutput(int sessionId, int uid, int pid,
1375 const audio_attributes_t* attr)
Andreas Huber20111aa2009-07-14 16:56:47 -07001376 : mCallback(NULL),
Eric Laurenta514bdb2010-06-21 09:27:30 -07001377 mCallbackCookie(NULL),
Marco Nelissen6b74d672012-02-28 16:07:44 -08001378 mCallbackData(NULL),
Marco Nelissen4110c102012-03-29 09:31:28 -07001379 mBytesWritten(0),
Andy Hungd1c74342015-07-07 16:54:23 -07001380 mStreamType(AUDIO_STREAM_MUSIC),
Andy Hungd1c74342015-07-07 16:54:23 -07001381 mLeftVolume(1.0),
1382 mRightVolume(1.0),
1383 mPlaybackRate(AUDIO_PLAYBACK_RATE_DEFAULT),
1384 mSampleRateHz(0),
1385 mMsecsPerFrame(0),
1386 mFrameSize(0),
Eric Laurent1948eb32012-04-13 16:50:19 -07001387 mSessionId(sessionId),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001388 mUid(uid),
Marco Nelissend457c972014-02-11 08:47:07 -08001389 mPid(pid),
Andy Hungd1c74342015-07-07 16:54:23 -07001390 mSendLevel(0.0),
1391 mAuxEffectId(0),
1392 mFlags(AUDIO_OUTPUT_FLAG_NONE)
1393{
Steve Block3856b092011-10-20 11:56:00 +01001394 ALOGV("AudioOutput(%d)", sessionId);
Eric Laurent43562692015-07-15 16:49:07 -07001395 if (attr != NULL) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001396 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1397 if (mAttributes != NULL) {
1398 memcpy(mAttributes, attr, sizeof(audio_attributes_t));
1399 mStreamType = audio_attributes_to_stream_type(attr);
1400 }
1401 } else {
1402 mAttributes = NULL;
Eric Laurent43562692015-07-15 16:49:07 -07001403 }
1404
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001405 setMinBufferCount();
1406}
1407
1408MediaPlayerService::AudioOutput::~AudioOutput()
1409{
1410 close();
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001411 free(mAttributes);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001412 delete mCallbackData;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001413}
1414
Andy Hungd1c74342015-07-07 16:54:23 -07001415//static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001416void MediaPlayerService::AudioOutput::setMinBufferCount()
1417{
1418 char value[PROPERTY_VALUE_MAX];
1419 if (property_get("ro.kernel.qemu", value, 0)) {
1420 mIsOnEmulator = true;
1421 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1422 }
1423}
1424
Andy Hungd1c74342015-07-07 16:54:23 -07001425// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001426bool MediaPlayerService::AudioOutput::isOnEmulator()
1427{
Andy Hungd1c74342015-07-07 16:54:23 -07001428 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001429 return mIsOnEmulator;
1430}
1431
Andy Hungd1c74342015-07-07 16:54:23 -07001432// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001433int MediaPlayerService::AudioOutput::getMinBufferCount()
1434{
Andy Hungd1c74342015-07-07 16:54:23 -07001435 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001436 return mMinBufferCount;
1437}
1438
1439ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1440{
Andy Hungd1c74342015-07-07 16:54:23 -07001441 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001442 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001443 return mTrack->frameCount() * mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001444}
1445
1446ssize_t MediaPlayerService::AudioOutput::frameCount() const
1447{
Andy Hungd1c74342015-07-07 16:54:23 -07001448 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001449 if (mTrack == 0) return NO_INIT;
1450 return mTrack->frameCount();
1451}
1452
1453ssize_t MediaPlayerService::AudioOutput::channelCount() const
1454{
Andy Hungd1c74342015-07-07 16:54:23 -07001455 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001456 if (mTrack == 0) return NO_INIT;
1457 return mTrack->channelCount();
1458}
1459
1460ssize_t MediaPlayerService::AudioOutput::frameSize() const
1461{
Andy Hungd1c74342015-07-07 16:54:23 -07001462 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001463 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001464 return mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001465}
1466
1467uint32_t MediaPlayerService::AudioOutput::latency () const
1468{
Andy Hungd1c74342015-07-07 16:54:23 -07001469 Mutex::Autolock lock(mLock);
Eric Laurentdb354e52012-03-05 17:27:11 -08001470 if (mTrack == 0) return 0;
1471 return mTrack->latency();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001472}
1473
1474float MediaPlayerService::AudioOutput::msecsPerFrame() const
1475{
Andy Hungd1c74342015-07-07 16:54:23 -07001476 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001477 return mMsecsPerFrame;
1478}
1479
Marco Nelissen4110c102012-03-29 09:31:28 -07001480status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position) const
Eric Laurent342e9cf2010-01-19 17:37:09 -08001481{
Andy Hungd1c74342015-07-07 16:54:23 -07001482 Mutex::Autolock lock(mLock);
Eric Laurent342e9cf2010-01-19 17:37:09 -08001483 if (mTrack == 0) return NO_INIT;
1484 return mTrack->getPosition(position);
1485}
1486
Lajos Molnar06ad1522014-08-28 07:27:44 -07001487status_t MediaPlayerService::AudioOutput::getTimestamp(AudioTimestamp &ts) const
1488{
Andy Hungd1c74342015-07-07 16:54:23 -07001489 Mutex::Autolock lock(mLock);
Lajos Molnar06ad1522014-08-28 07:27:44 -07001490 if (mTrack == 0) return NO_INIT;
1491 return mTrack->getTimestamp(ts);
1492}
1493
Marco Nelissen4110c102012-03-29 09:31:28 -07001494status_t MediaPlayerService::AudioOutput::getFramesWritten(uint32_t *frameswritten) const
1495{
Andy Hungd1c74342015-07-07 16:54:23 -07001496 Mutex::Autolock lock(mLock);
Marco Nelissen4110c102012-03-29 09:31:28 -07001497 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001498 *frameswritten = mBytesWritten / mFrameSize;
Marco Nelissen4110c102012-03-29 09:31:28 -07001499 return OK;
1500}
1501
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001502status_t MediaPlayerService::AudioOutput::setParameters(const String8& keyValuePairs)
1503{
Andy Hungd1c74342015-07-07 16:54:23 -07001504 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001505 if (mTrack == 0) return NO_INIT;
1506 return mTrack->setParameters(keyValuePairs);
1507}
1508
1509String8 MediaPlayerService::AudioOutput::getParameters(const String8& keys)
1510{
Andy Hungd1c74342015-07-07 16:54:23 -07001511 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001512 if (mTrack == 0) return String8::empty();
1513 return mTrack->getParameters(keys);
1514}
1515
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001516void MediaPlayerService::AudioOutput::setAudioAttributes(const audio_attributes_t * attributes) {
Andy Hungd1c74342015-07-07 16:54:23 -07001517 Mutex::Autolock lock(mLock);
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001518 if (attributes == NULL) {
1519 free(mAttributes);
1520 mAttributes = NULL;
1521 } else {
1522 if (mAttributes == NULL) {
1523 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1524 }
1525 memcpy(mAttributes, attributes, sizeof(audio_attributes_t));
Eric Laurent43562692015-07-15 16:49:07 -07001526 mStreamType = audio_attributes_to_stream_type(attributes);
1527 }
1528}
1529
1530void MediaPlayerService::AudioOutput::setAudioStreamType(audio_stream_type_t streamType)
1531{
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001532 Mutex::Autolock lock(mLock);
Eric Laurent43562692015-07-15 16:49:07 -07001533 // do not allow direct stream type modification if attributes have been set
1534 if (mAttributes == NULL) {
1535 mStreamType = streamType;
1536 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001537}
1538
Andy Hungd1c74342015-07-07 16:54:23 -07001539void MediaPlayerService::AudioOutput::deleteRecycledTrack_l()
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001540{
Andy Hungd1c74342015-07-07 16:54:23 -07001541 ALOGV("deleteRecycledTrack_l");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001542 if (mRecycledTrack != 0) {
1543
1544 if (mCallbackData != NULL) {
1545 mCallbackData->setOutput(NULL);
1546 mCallbackData->endTrackSwitch();
1547 }
1548
1549 if ((mRecycledTrack->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) {
1550 mRecycledTrack->flush();
1551 }
1552 // An offloaded track isn't flushed because the STREAM_END is reported
1553 // slightly prematurely to allow time for the gapless track switch
1554 // but this means that if we decide not to recycle the track there
1555 // could be a small amount of residual data still playing. We leave
1556 // AudioFlinger to drain the track.
1557
1558 mRecycledTrack.clear();
Andy Hungd1c74342015-07-07 16:54:23 -07001559 close_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001560 delete mCallbackData;
1561 mCallbackData = NULL;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001562 }
1563}
1564
Andy Hungd1c74342015-07-07 16:54:23 -07001565void MediaPlayerService::AudioOutput::close_l()
1566{
1567 mTrack.clear();
1568}
1569
Andreas Huber20111aa2009-07-14 16:56:47 -07001570status_t MediaPlayerService::AudioOutput::open(
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001571 uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
1572 audio_format_t format, int bufferCount,
Eric Laurent1948eb32012-04-13 16:50:19 -07001573 AudioCallback cb, void *cookie,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001574 audio_output_flags_t flags,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001575 const audio_offload_info_t *offloadInfo,
Andy Hung179652e2015-05-31 22:49:46 -07001576 bool doNotReconnect,
1577 uint32_t suggestedFrameCount)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001578{
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001579 ALOGV("open(%u, %d, 0x%x, 0x%x, %d, %d 0x%x)", sampleRate, channelCount, channelMask,
1580 format, bufferCount, mSessionId, flags);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001581
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001582 // offloading is only supported in callback mode for now.
1583 // offloadInfo must be present if offload flag is set
1584 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) &&
1585 ((cb == NULL) || (offloadInfo == NULL))) {
1586 return BAD_VALUE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001587 }
1588
Andy Hung179652e2015-05-31 22:49:46 -07001589 // compute frame count for the AudioTrack internal buffer
1590 size_t frameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001591 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1592 frameCount = 0; // AudioTrack will get frame count from AudioFlinger
1593 } else {
Andy Hung179652e2015-05-31 22:49:46 -07001594 // try to estimate the buffer processing fetch size from AudioFlinger.
1595 // framesPerBuffer is approximate and generally correct, except when it's not :-).
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001596 uint32_t afSampleRate;
1597 size_t afFrameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001598 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1599 return NO_INIT;
1600 }
1601 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1602 return NO_INIT;
1603 }
Andy Hung179652e2015-05-31 22:49:46 -07001604 const size_t framesPerBuffer =
1605 (unsigned long long)sampleRate * afFrameCount / afSampleRate;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001606
Andy Hung179652e2015-05-31 22:49:46 -07001607 if (bufferCount == 0) {
1608 // use suggestedFrameCount
1609 bufferCount = (suggestedFrameCount + framesPerBuffer - 1) / framesPerBuffer;
1610 }
1611 // Check argument bufferCount against the mininum buffer count
1612 if (bufferCount != 0 && bufferCount < mMinBufferCount) {
1613 ALOGV("bufferCount (%d) increased to %d", bufferCount, mMinBufferCount);
1614 bufferCount = mMinBufferCount;
1615 }
1616 // if frameCount is 0, then AudioTrack will get frame count from AudioFlinger
1617 // which will be the minimum size permitted.
1618 frameCount = bufferCount * framesPerBuffer;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001619 }
Andreas Huber20111aa2009-07-14 16:56:47 -07001620
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001621 if (channelMask == CHANNEL_MASK_USE_CHANNEL_ORDER) {
Glenn Kastenab334fd2012-03-14 12:56:06 -07001622 channelMask = audio_channel_out_mask_from_count(channelCount);
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001623 if (0 == channelMask) {
1624 ALOGE("open() error, can\'t derive mask for %d audio channels", channelCount);
1625 return NO_INIT;
1626 }
1627 }
Eric Laurent1948eb32012-04-13 16:50:19 -07001628
Andy Hungd1c74342015-07-07 16:54:23 -07001629 Mutex::Autolock lock(mLock);
Andy Hung179652e2015-05-31 22:49:46 -07001630 mCallback = cb;
1631 mCallbackCookie = cookie;
1632
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001633 // Check whether we can recycle the track
1634 bool reuse = false;
1635 bool bothOffloaded = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001636
Glenn Kasten2799d742013-05-30 14:33:29 -07001637 if (mRecycledTrack != 0) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001638 // check whether we are switching between two offloaded tracks
1639 bothOffloaded = (flags & mRecycledTrack->getFlags()
1640 & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0;
Marco Nelissen67295b52012-06-11 14:52:53 -07001641
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001642 // check if the existing track can be reused as-is, or if a new track needs to be created.
1643 reuse = true;
1644
Marco Nelissen67295b52012-06-11 14:52:53 -07001645 if ((mCallbackData == NULL && mCallback != NULL) ||
1646 (mCallbackData != NULL && mCallback == NULL)) {
1647 // recycled track uses callbacks but the caller wants to use writes, or vice versa
1648 ALOGV("can't chain callback and write");
1649 reuse = false;
1650 } else if ((mRecycledTrack->getSampleRate() != sampleRate) ||
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001651 (mRecycledTrack->channelCount() != (uint32_t)channelCount) ) {
1652 ALOGV("samplerate, channelcount differ: %u/%u Hz, %u/%d ch",
Marco Nelissen67295b52012-06-11 14:52:53 -07001653 mRecycledTrack->getSampleRate(), sampleRate,
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001654 mRecycledTrack->channelCount(), channelCount);
Marco Nelissen67295b52012-06-11 14:52:53 -07001655 reuse = false;
1656 } else if (flags != mFlags) {
1657 ALOGV("output flags differ %08x/%08x", flags, mFlags);
1658 reuse = false;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001659 } else if (mRecycledTrack->format() != format) {
1660 reuse = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001661 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001662 } else {
1663 ALOGV("no track available to recycle");
1664 }
1665
1666 ALOGV_IF(bothOffloaded, "both tracks offloaded");
1667
1668 // If we can't recycle and both tracks are offloaded
1669 // we must close the previous output before opening a new one
1670 if (bothOffloaded && !reuse) {
1671 ALOGV("both offloaded and not recycling");
Andy Hungd1c74342015-07-07 16:54:23 -07001672 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001673 }
1674
1675 sp<AudioTrack> t;
1676 CallbackData *newcbd = NULL;
1677
1678 // We don't attempt to create a new track if we are recycling an
1679 // offloaded track. But, if we are recycling a non-offloaded or we
1680 // are switching where one is offloaded and one isn't then we create
1681 // the new track in advance so that we can read additional stream info
1682
1683 if (!(reuse && bothOffloaded)) {
1684 ALOGV("creating new AudioTrack");
1685
1686 if (mCallback != NULL) {
1687 newcbd = new CallbackData(this);
1688 t = new AudioTrack(
1689 mStreamType,
1690 sampleRate,
1691 format,
1692 channelMask,
1693 frameCount,
1694 flags,
1695 CallbackWrapper,
1696 newcbd,
1697 0, // notification frames
1698 mSessionId,
1699 AudioTrack::TRANSFER_CALLBACK,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001700 offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -08001701 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001702 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001703 mAttributes,
1704 doNotReconnect);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001705 } else {
1706 t = new AudioTrack(
1707 mStreamType,
1708 sampleRate,
1709 format,
1710 channelMask,
1711 frameCount,
1712 flags,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001713 NULL, // callback
1714 NULL, // user data
1715 0, // notification frames
1716 mSessionId,
1717 AudioTrack::TRANSFER_DEFAULT,
1718 NULL, // offload info
Marco Nelissend457c972014-02-11 08:47:07 -08001719 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001720 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001721 mAttributes,
1722 doNotReconnect);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001723 }
1724
1725 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1726 ALOGE("Unable to create audio track");
1727 delete newcbd;
Glenn Kasten3e98ecd2015-05-18 13:13:24 -07001728 // t goes out of scope, so reference count drops to zero
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001729 return NO_INIT;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001730 } else {
1731 // successful AudioTrack initialization implies a legacy stream type was generated
1732 // from the audio attributes
1733 mStreamType = t->streamType();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001734 }
1735 }
1736
1737 if (reuse) {
1738 CHECK(mRecycledTrack != NULL);
1739
1740 if (!bothOffloaded) {
1741 if (mRecycledTrack->frameCount() != t->frameCount()) {
1742 ALOGV("framecount differs: %u/%u frames",
1743 mRecycledTrack->frameCount(), t->frameCount());
1744 reuse = false;
1745 }
1746 }
1747
Marco Nelissen67295b52012-06-11 14:52:53 -07001748 if (reuse) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001749 ALOGV("chaining to next output and recycling track");
Andy Hungd1c74342015-07-07 16:54:23 -07001750 close_l();
Marco Nelissen67295b52012-06-11 14:52:53 -07001751 mTrack = mRecycledTrack;
Glenn Kasten2799d742013-05-30 14:33:29 -07001752 mRecycledTrack.clear();
Marco Nelissen67295b52012-06-11 14:52:53 -07001753 if (mCallbackData != NULL) {
1754 mCallbackData->setOutput(this);
1755 }
Marco Nelissen67295b52012-06-11 14:52:53 -07001756 delete newcbd;
1757 return OK;
1758 }
Marco Nelissen67295b52012-06-11 14:52:53 -07001759 }
1760
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001761 // we're not going to reuse the track, unblock and flush it
1762 // this was done earlier if both tracks are offloaded
1763 if (!bothOffloaded) {
Andy Hungd1c74342015-07-07 16:54:23 -07001764 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001765 }
1766
1767 CHECK((t != NULL) && ((mCallback == NULL) || (newcbd != NULL)));
1768
Marco Nelissen67295b52012-06-11 14:52:53 -07001769 mCallbackData = newcbd;
Steve Block3856b092011-10-20 11:56:00 +01001770 ALOGV("setVolume");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001771 t->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07001772
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001773 mSampleRateHz = sampleRate;
Preetam Singh Ranawat2e17eef2015-08-12 12:11:46 -07001774 mFlags = flags;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001775 mMsecsPerFrame = 1E3f / (mPlaybackRate.mSpeed * sampleRate);
Andy Hungd1c74342015-07-07 16:54:23 -07001776 mFrameSize = t->frameSize();
Marco Nelissen99448602012-04-02 12:16:49 -07001777 uint32_t pos;
1778 if (t->getPosition(&pos) == OK) {
Andy Hungd1c74342015-07-07 16:54:23 -07001779 mBytesWritten = uint64_t(pos) * mFrameSize;
Marco Nelissen99448602012-04-02 12:16:49 -07001780 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001781 mTrack = t;
Eric Laurent2beeb502010-07-16 07:43:46 -07001782
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001783 status_t res = NO_ERROR;
Wei Jia0162d002015-06-09 11:59:33 -07001784 // Note some output devices may give us a direct track even though we don't specify it.
1785 // Example: Line application b/17459982.
Preetam Singh Ranawat2e17eef2015-08-12 12:11:46 -07001786 if ((t->getFlags() & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) {
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001787 res = t->setPlaybackRate(mPlaybackRate);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001788 if (res == NO_ERROR) {
1789 t->setAuxEffectSendLevel(mSendLevel);
1790 res = t->attachAuxEffect(mAuxEffectId);
1791 }
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001792 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001793 ALOGV("open() DONE status %d", res);
1794 return res;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001795}
1796
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001797status_t MediaPlayerService::AudioOutput::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001798{
Steve Block3856b092011-10-20 11:56:00 +01001799 ALOGV("start");
Andy Hungd1c74342015-07-07 16:54:23 -07001800 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001801 if (mCallbackData != NULL) {
1802 mCallbackData->endTrackSwitch();
1803 }
Glenn Kasten2799d742013-05-30 14:33:29 -07001804 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001805 mTrack->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07001806 mTrack->setAuxEffectSendLevel(mSendLevel);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001807 return mTrack->start();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001808 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001809 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001810}
1811
Marco Nelissen6b74d672012-02-28 16:07:44 -08001812void MediaPlayerService::AudioOutput::setNextOutput(const sp<AudioOutput>& nextOutput) {
Andy Hungd1c74342015-07-07 16:54:23 -07001813 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001814 mNextOutput = nextOutput;
1815}
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08001816
Marco Nelissen6b74d672012-02-28 16:07:44 -08001817void MediaPlayerService::AudioOutput::switchToNextOutput() {
1818 ALOGV("switchToNextOutput");
Andy Hungd1c74342015-07-07 16:54:23 -07001819
1820 // Try to acquire the callback lock before moving track (without incurring deadlock).
1821 const unsigned kMaxSwitchTries = 100;
1822 Mutex::Autolock lock(mLock);
1823 for (unsigned tries = 0;;) {
1824 if (mTrack == 0) {
1825 return;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001826 }
Andy Hungd1c74342015-07-07 16:54:23 -07001827 if (mNextOutput != NULL && mNextOutput != this) {
1828 if (mCallbackData != NULL) {
1829 // two alternative approaches
1830#if 1
1831 CallbackData *callbackData = mCallbackData;
1832 mLock.unlock();
1833 // proper acquisition sequence
1834 callbackData->lock();
1835 mLock.lock();
1836 // Caution: it is unlikely that someone deleted our callback or changed our target
1837 if (callbackData != mCallbackData || mNextOutput == NULL || mNextOutput == this) {
1838 // fatal if we are starved out.
1839 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
1840 "switchToNextOutput() cannot obtain correct lock sequence");
1841 callbackData->unlock();
1842 continue;
1843 }
1844 callbackData->mSwitching = true; // begin track switch
1845#else
1846 // tryBeginTrackSwitch() returns false if the callback has the lock.
1847 if (!mCallbackData->tryBeginTrackSwitch()) {
1848 // fatal if we are starved out.
1849 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
1850 "switchToNextOutput() cannot obtain callback lock");
1851 mLock.unlock();
1852 usleep(5 * 1000 /* usec */); // allow callback to use AudioOutput
1853 mLock.lock();
1854 continue;
1855 }
1856#endif
1857 }
1858
1859 Mutex::Autolock nextLock(mNextOutput->mLock);
1860
1861 // If the next output track is not NULL, then it has been
1862 // opened already for playback.
1863 // This is possible even without the next player being started,
1864 // for example, the next player could be prepared and seeked.
1865 //
1866 // Presuming it isn't advisable to force the track over.
1867 if (mNextOutput->mTrack == NULL) {
1868 ALOGD("Recycling track for gapless playback");
1869 delete mNextOutput->mCallbackData;
1870 mNextOutput->mCallbackData = mCallbackData;
1871 mNextOutput->mRecycledTrack = mTrack;
1872 mNextOutput->mSampleRateHz = mSampleRateHz;
1873 mNextOutput->mMsecsPerFrame = mMsecsPerFrame;
1874 mNextOutput->mBytesWritten = mBytesWritten;
1875 mNextOutput->mFlags = mFlags;
1876 mNextOutput->mFrameSize = mFrameSize;
1877 close_l();
1878 mCallbackData = NULL; // destruction handled by mNextOutput
1879 } else {
1880 ALOGW("Ignoring gapless playback because next player has already started");
1881 // remove track in case resource needed for future players.
1882 if (mCallbackData != NULL) {
1883 mCallbackData->endTrackSwitch(); // release lock for callbacks before close.
1884 }
1885 close_l();
1886 }
1887 }
1888 break;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001889 }
1890}
1891
Wei Jia7d3f4df2015-03-03 15:28:00 -08001892ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001893{
Andy Hungd1c74342015-07-07 16:54:23 -07001894 Mutex::Autolock lock(mLock);
Glenn Kastenadad3d72014-02-21 14:51:43 -08001895 LOG_ALWAYS_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
Andreas Huber20111aa2009-07-14 16:56:47 -07001896
Steve Block3856b092011-10-20 11:56:00 +01001897 //ALOGV("write(%p, %u)", buffer, size);
Glenn Kasten2799d742013-05-30 14:33:29 -07001898 if (mTrack != 0) {
Wei Jia7d3f4df2015-03-03 15:28:00 -08001899 ssize_t ret = mTrack->write(buffer, size, blocking);
Andy Hunga31335a2014-08-20 17:37:59 -07001900 if (ret >= 0) {
1901 mBytesWritten += ret;
1902 }
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001903 return ret;
1904 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001905 return NO_INIT;
1906}
1907
1908void MediaPlayerService::AudioOutput::stop()
1909{
Steve Block3856b092011-10-20 11:56:00 +01001910 ALOGV("stop");
Andy Hungd1c74342015-07-07 16:54:23 -07001911 Mutex::Autolock lock(mLock);
Andy Hungda17c042015-06-01 15:53:14 -07001912 mBytesWritten = 0;
Glenn Kasten2799d742013-05-30 14:33:29 -07001913 if (mTrack != 0) mTrack->stop();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001914}
1915
1916void MediaPlayerService::AudioOutput::flush()
1917{
Steve Block3856b092011-10-20 11:56:00 +01001918 ALOGV("flush");
Andy Hungd1c74342015-07-07 16:54:23 -07001919 Mutex::Autolock lock(mLock);
Andy Hungda17c042015-06-01 15:53:14 -07001920 mBytesWritten = 0;
Glenn Kasten2799d742013-05-30 14:33:29 -07001921 if (mTrack != 0) mTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001922}
1923
1924void MediaPlayerService::AudioOutput::pause()
1925{
Steve Block3856b092011-10-20 11:56:00 +01001926 ALOGV("pause");
Andy Hungd1c74342015-07-07 16:54:23 -07001927 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07001928 if (mTrack != 0) mTrack->pause();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001929}
1930
1931void MediaPlayerService::AudioOutput::close()
1932{
Steve Block3856b092011-10-20 11:56:00 +01001933 ALOGV("close");
Andy Hungd1c74342015-07-07 16:54:23 -07001934 Mutex::Autolock lock(mLock);
1935 close_l();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001936}
1937
1938void MediaPlayerService::AudioOutput::setVolume(float left, float right)
1939{
Steve Block3856b092011-10-20 11:56:00 +01001940 ALOGV("setVolume(%f, %f)", left, right);
Andy Hungd1c74342015-07-07 16:54:23 -07001941 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001942 mLeftVolume = left;
1943 mRightVolume = right;
Glenn Kasten2799d742013-05-30 14:33:29 -07001944 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001945 mTrack->setVolume(left, right);
1946 }
1947}
1948
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001949status_t MediaPlayerService::AudioOutput::setPlaybackRate(const AudioPlaybackRate &rate)
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001950{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001951 ALOGV("setPlaybackRate(%f %f %d %d)",
1952 rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Andy Hungd1c74342015-07-07 16:54:23 -07001953 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001954 if (mTrack == 0) {
1955 // remember rate so that we can set it when the track is opened
1956 mPlaybackRate = rate;
1957 return OK;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001958 }
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001959 status_t res = mTrack->setPlaybackRate(rate);
1960 if (res != NO_ERROR) {
1961 return res;
1962 }
1963 // rate.mSpeed is always greater than 0 if setPlaybackRate succeeded
1964 CHECK_GT(rate.mSpeed, 0.f);
1965 mPlaybackRate = rate;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001966 if (mSampleRateHz != 0) {
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001967 mMsecsPerFrame = 1E3f / (rate.mSpeed * mSampleRateHz);
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001968 }
1969 return res;
1970}
1971
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001972status_t MediaPlayerService::AudioOutput::getPlaybackRate(AudioPlaybackRate *rate)
1973{
1974 ALOGV("setPlaybackRate");
Andy Hungd1c74342015-07-07 16:54:23 -07001975 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001976 if (mTrack == 0) {
1977 return NO_INIT;
1978 }
1979 *rate = mTrack->getPlaybackRate();
1980 return NO_ERROR;
1981}
1982
Eric Laurent2beeb502010-07-16 07:43:46 -07001983status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
1984{
Steve Block3856b092011-10-20 11:56:00 +01001985 ALOGV("setAuxEffectSendLevel(%f)", level);
Andy Hungd1c74342015-07-07 16:54:23 -07001986 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07001987 mSendLevel = level;
Glenn Kasten2799d742013-05-30 14:33:29 -07001988 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07001989 return mTrack->setAuxEffectSendLevel(level);
1990 }
1991 return NO_ERROR;
1992}
1993
1994status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
1995{
Steve Block3856b092011-10-20 11:56:00 +01001996 ALOGV("attachAuxEffect(%d)", effectId);
Andy Hungd1c74342015-07-07 16:54:23 -07001997 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07001998 mAuxEffectId = effectId;
Glenn Kasten2799d742013-05-30 14:33:29 -07001999 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002000 return mTrack->attachAuxEffect(effectId);
2001 }
2002 return NO_ERROR;
2003}
2004
Andreas Huber20111aa2009-07-14 16:56:47 -07002005// static
2006void MediaPlayerService::AudioOutput::CallbackWrapper(
Glenn Kastend217a8c2011-06-01 15:20:35 -07002007 int event, void *cookie, void *info) {
Steve Block3856b092011-10-20 11:56:00 +01002008 //ALOGV("callbackwrapper");
Marco Nelissen6b74d672012-02-28 16:07:44 -08002009 CallbackData *data = (CallbackData*)cookie;
Andy Hungd1c74342015-07-07 16:54:23 -07002010 // lock to ensure we aren't caught in the middle of a track switch.
Marco Nelissen6b74d672012-02-28 16:07:44 -08002011 data->lock();
2012 AudioOutput *me = data->getOutput();
Andreas Huber20111aa2009-07-14 16:56:47 -07002013 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002014 if (me == NULL) {
2015 // no output set, likely because the track was scheduled to be reused
2016 // by another player, but the format turned out to be incompatible.
2017 data->unlock();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002018 if (buffer != NULL) {
2019 buffer->size = 0;
2020 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08002021 return;
2022 }
Andreas Huber20111aa2009-07-14 16:56:47 -07002023
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002024 switch(event) {
2025 case AudioTrack::EVENT_MORE_DATA: {
2026 size_t actualSize = (*me->mCallback)(
2027 me, buffer->raw, buffer->size, me->mCallbackCookie,
2028 CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002029
Andy Hung719b46b2015-05-31 22:18:25 -07002030 // Log when no data is returned from the callback.
2031 // (1) We may have no data (especially with network streaming sources).
2032 // (2) We may have reached the EOS and the audio track is not stopped yet.
2033 // Note that AwesomePlayer/AudioPlayer will only return zero size when it reaches the EOS.
2034 // NuPlayerRenderer will return zero when it doesn't have data (it doesn't block to fill).
2035 //
2036 // This is a benign busy-wait, with the next data request generated 10 ms or more later;
2037 // nevertheless for power reasons, we don't want to see too many of these.
Andreas Huber2e8ffaf2010-02-18 16:45:13 -08002038
Andy Hung719b46b2015-05-31 22:18:25 -07002039 ALOGV_IF(actualSize == 0 && buffer->size > 0, "callbackwrapper: empty buffer returned");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002040
Andy Hung719b46b2015-05-31 22:18:25 -07002041 me->mBytesWritten += actualSize; // benign race with reader.
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002042 buffer->size = actualSize;
2043 } break;
2044
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002045 case AudioTrack::EVENT_STREAM_END:
Andy Hung719b46b2015-05-31 22:18:25 -07002046 // currently only occurs for offloaded callbacks
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002047 ALOGV("callbackwrapper: deliver EVENT_STREAM_END");
2048 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2049 me->mCallbackCookie, CB_EVENT_STREAM_END);
2050 break;
2051
2052 case AudioTrack::EVENT_NEW_IAUDIOTRACK :
2053 ALOGV("callbackwrapper: deliver EVENT_TEAR_DOWN");
2054 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2055 me->mCallbackCookie, CB_EVENT_TEAR_DOWN);
2056 break;
2057
Glenn Kasten421743b2015-06-01 08:18:08 -07002058 case AudioTrack::EVENT_UNDERRUN:
Andy Hung719b46b2015-05-31 22:18:25 -07002059 // This occurs when there is no data available, typically
Glenn Kasten421743b2015-06-01 08:18:08 -07002060 // when there is a failure to supply data to the AudioTrack. It can also
2061 // occur in non-offloaded mode when the audio device comes out of standby.
2062 //
Andy Hung719b46b2015-05-31 22:18:25 -07002063 // If an AudioTrack underruns it outputs silence. Since this happens suddenly
2064 // it may sound like an audible pop or glitch.
2065 //
2066 // The underrun event is sent once per track underrun; the condition is reset
2067 // when more data is sent to the AudioTrack.
Glenn Kasten421743b2015-06-01 08:18:08 -07002068 ALOGI("callbackwrapper: EVENT_UNDERRUN (discarded)");
2069 break;
2070
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002071 default:
2072 ALOGE("received unknown event type: %d inside CallbackWrapper !", event);
Andreas Huber51c1e0e2011-04-04 11:43:40 -07002073 }
2074
Marco Nelissen6b74d672012-02-28 16:07:44 -08002075 data->unlock();
Andreas Huber20111aa2009-07-14 16:56:47 -07002076}
2077
Marco Nelissen4110c102012-03-29 09:31:28 -07002078int MediaPlayerService::AudioOutput::getSessionId() const
Eric Laurent8c563ed2010-10-07 18:23:03 -07002079{
Andy Hungd1c74342015-07-07 16:54:23 -07002080 Mutex::Autolock lock(mLock);
Eric Laurent8c563ed2010-10-07 18:23:03 -07002081 return mSessionId;
2082}
2083
Eric Laurent6f59db12013-07-26 17:16:50 -07002084uint32_t MediaPlayerService::AudioOutput::getSampleRate() const
2085{
Andy Hungd1c74342015-07-07 16:54:23 -07002086 Mutex::Autolock lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -07002087 if (mTrack == 0) return 0;
2088 return mTrack->getSampleRate();
2089}
2090
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002091////////////////////////////////////////////////////////////////////////////////
2092
2093struct CallbackThread : public Thread {
2094 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
2095 MediaPlayerBase::AudioSink::AudioCallback cb,
2096 void *cookie);
2097
2098protected:
2099 virtual ~CallbackThread();
2100
2101 virtual bool threadLoop();
2102
2103private:
2104 wp<MediaPlayerBase::AudioSink> mSink;
2105 MediaPlayerBase::AudioSink::AudioCallback mCallback;
2106 void *mCookie;
2107 void *mBuffer;
2108 size_t mBufferSize;
2109
2110 CallbackThread(const CallbackThread &);
2111 CallbackThread &operator=(const CallbackThread &);
2112};
2113
2114CallbackThread::CallbackThread(
2115 const wp<MediaPlayerBase::AudioSink> &sink,
2116 MediaPlayerBase::AudioSink::AudioCallback cb,
2117 void *cookie)
2118 : mSink(sink),
2119 mCallback(cb),
2120 mCookie(cookie),
2121 mBuffer(NULL),
2122 mBufferSize(0) {
2123}
2124
2125CallbackThread::~CallbackThread() {
2126 if (mBuffer) {
2127 free(mBuffer);
2128 mBuffer = NULL;
2129 }
2130}
2131
2132bool CallbackThread::threadLoop() {
2133 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
2134 if (sink == NULL) {
2135 return false;
2136 }
2137
2138 if (mBuffer == NULL) {
2139 mBufferSize = sink->bufferSize();
2140 mBuffer = malloc(mBufferSize);
2141 }
2142
2143 size_t actualSize =
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002144 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie,
2145 MediaPlayerBase::AudioSink::CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002146
2147 if (actualSize > 0) {
2148 sink->write(mBuffer, actualSize);
Andy Hunga31335a2014-08-20 17:37:59 -07002149 // Could return false on sink->write() error or short count.
2150 // Not necessarily appropriate but would work for AudioCache behavior.
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002151 }
2152
2153 return true;
2154}
2155
2156////////////////////////////////////////////////////////////////////////////////
2157
Gloria Wang7cf180c2011-02-19 18:37:57 -08002158void MediaPlayerService::addBatteryData(uint32_t params)
2159{
2160 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002161
2162 int32_t time = systemTime() / 1000000L;
2163
2164 // change audio output devices. This notification comes from AudioFlinger
2165 if ((params & kBatteryDataSpeakerOn)
2166 || (params & kBatteryDataOtherAudioDeviceOn)) {
2167
2168 int deviceOn[NUM_AUDIO_DEVICES];
2169 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2170 deviceOn[i] = 0;
2171 }
2172
2173 if ((params & kBatteryDataSpeakerOn)
2174 && (params & kBatteryDataOtherAudioDeviceOn)) {
2175 deviceOn[SPEAKER_AND_OTHER] = 1;
2176 } else if (params & kBatteryDataSpeakerOn) {
2177 deviceOn[SPEAKER] = 1;
2178 } else {
2179 deviceOn[OTHER_AUDIO_DEVICE] = 1;
2180 }
2181
2182 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2183 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
2184
2185 if (mBatteryAudio.refCount > 0) { // if playing audio
2186 if (!deviceOn[i]) {
2187 mBatteryAudio.lastTime[i] += time;
2188 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2189 mBatteryAudio.lastTime[i] = 0;
2190 } else {
2191 mBatteryAudio.lastTime[i] = 0 - time;
2192 }
2193 }
2194
2195 mBatteryAudio.deviceOn[i] = deviceOn[i];
2196 }
2197 }
2198 return;
2199 }
2200
Marco Nelissenb7848f12014-12-04 08:57:56 -08002201 // an audio stream is started
Gloria Wang9ee159b2011-02-24 14:51:45 -08002202 if (params & kBatteryDataAudioFlingerStart) {
2203 // record the start time only if currently no other audio
2204 // is being played
2205 if (mBatteryAudio.refCount == 0) {
2206 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2207 if (mBatteryAudio.deviceOn[i]) {
2208 mBatteryAudio.lastTime[i] -= time;
2209 }
2210 }
2211 }
2212
2213 mBatteryAudio.refCount ++;
2214 return;
2215
2216 } else if (params & kBatteryDataAudioFlingerStop) {
2217 if (mBatteryAudio.refCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002218 ALOGW("Battery track warning: refCount is <= 0");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002219 return;
2220 }
2221
2222 // record the stop time only if currently this is the only
2223 // audio being played
2224 if (mBatteryAudio.refCount == 1) {
2225 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2226 if (mBatteryAudio.deviceOn[i]) {
2227 mBatteryAudio.lastTime[i] += time;
2228 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2229 mBatteryAudio.lastTime[i] = 0;
2230 }
2231 }
2232 }
2233
2234 mBatteryAudio.refCount --;
2235 return;
2236 }
2237
Gloria Wang7cf180c2011-02-19 18:37:57 -08002238 int uid = IPCThreadState::self()->getCallingUid();
2239 if (uid == AID_MEDIA) {
2240 return;
2241 }
2242 int index = mBatteryData.indexOfKey(uid);
Gloria Wang7cf180c2011-02-19 18:37:57 -08002243
2244 if (index < 0) { // create a new entry for this UID
2245 BatteryUsageInfo info;
2246 info.audioTotalTime = 0;
2247 info.videoTotalTime = 0;
2248 info.audioLastTime = 0;
2249 info.videoLastTime = 0;
2250 info.refCount = 0;
2251
Gloria Wang9ee159b2011-02-24 14:51:45 -08002252 if (mBatteryData.add(uid, info) == NO_MEMORY) {
Steve Block29357bc2012-01-06 19:20:56 +00002253 ALOGE("Battery track error: no memory for new app");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002254 return;
2255 }
Gloria Wang7cf180c2011-02-19 18:37:57 -08002256 }
2257
2258 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
2259
2260 if (params & kBatteryDataCodecStarted) {
2261 if (params & kBatteryDataTrackAudio) {
2262 info.audioLastTime -= time;
2263 info.refCount ++;
2264 }
2265 if (params & kBatteryDataTrackVideo) {
2266 info.videoLastTime -= time;
2267 info.refCount ++;
2268 }
2269 } else {
2270 if (info.refCount == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002271 ALOGW("Battery track warning: refCount is already 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002272 return;
2273 } else if (info.refCount < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00002274 ALOGE("Battery track error: refCount < 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002275 mBatteryData.removeItem(uid);
2276 return;
2277 }
2278
2279 if (params & kBatteryDataTrackAudio) {
2280 info.audioLastTime += time;
2281 info.refCount --;
2282 }
2283 if (params & kBatteryDataTrackVideo) {
2284 info.videoLastTime += time;
2285 info.refCount --;
2286 }
2287
2288 // no stream is being played by this UID
2289 if (info.refCount == 0) {
2290 info.audioTotalTime += info.audioLastTime;
2291 info.audioLastTime = 0;
2292 info.videoTotalTime += info.videoLastTime;
2293 info.videoLastTime = 0;
2294 }
2295 }
2296}
2297
2298status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
2299 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002300
2301 // audio output devices usage
2302 int32_t time = systemTime() / 1000000L; //in ms
2303 int32_t totalTime;
2304
2305 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2306 totalTime = mBatteryAudio.totalTime[i];
2307
2308 if (mBatteryAudio.deviceOn[i]
2309 && (mBatteryAudio.lastTime[i] != 0)) {
2310 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
2311 totalTime += tmpTime;
2312 }
2313
2314 reply->writeInt32(totalTime);
2315 // reset the total time
2316 mBatteryAudio.totalTime[i] = 0;
2317 }
2318
2319 // codec usage
Gloria Wang7cf180c2011-02-19 18:37:57 -08002320 BatteryUsageInfo info;
2321 int size = mBatteryData.size();
2322
2323 reply->writeInt32(size);
2324 int i = 0;
2325
2326 while (i < size) {
2327 info = mBatteryData.valueAt(i);
2328
2329 reply->writeInt32(mBatteryData.keyAt(i)); //UID
2330 reply->writeInt32(info.audioTotalTime);
2331 reply->writeInt32(info.videoTotalTime);
2332
2333 info.audioTotalTime = 0;
2334 info.videoTotalTime = 0;
2335
2336 // remove the UID entry where no stream is being played
2337 if (info.refCount <= 0) {
2338 mBatteryData.removeItemsAt(i);
2339 size --;
2340 i --;
2341 }
2342 i++;
2343 }
2344 return NO_ERROR;
2345}
nikoa64c8c72009-07-20 15:07:26 -07002346} // namespace android