blob: a41638155eb62cb7a5661300713b200d9bbd1d5a [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>
Marco Nelissen83b0fd92015-09-16 13:48:07 -070061#include <media/stagefright/Utils.h>
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +010062#include <media/stagefright/foundation/ADebug.h>
Marco Nelissenf09611f2015-02-13 14:12:42 -080063#include <media/stagefright/foundation/ALooperRoster.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070064#include <mediautils/BatteryNotifier.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080065
Dima Zavin64760242011-05-11 14:15:23 -070066#include <system/audio.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070067
Gloria Wang7cf180c2011-02-19 18:37:57 -080068#include <private/android_filesystem_config.h>
69
James Dong559bf282012-03-28 10:29:14 -070070#include "ActivityManager.h"
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080071#include "MediaRecorderClient.h"
72#include "MediaPlayerService.h"
73#include "MetadataRetrieverClient.h"
John Grossman44a7e422012-06-21 17:29:24 -070074#include "MediaPlayerFactory.h"
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080075
Nicolas Catania14d27472009-07-13 14:37:49 -070076#include "TestPlayerStub.h"
Andreas Huber20111aa2009-07-14 16:56:47 -070077#include "StagefrightPlayer.h"
Andreas Huberf9334412010-12-15 15:17:42 -080078#include "nuplayer/NuPlayerDriver.h"
Andreas Huber20111aa2009-07-14 16:56:47 -070079
Andreas Huber20111aa2009-07-14 16:56:47 -070080#include <OMX.h>
Nicolas Catania14d27472009-07-13 14:37:49 -070081
Andreas Hubered3e3e02012-03-26 11:13:27 -070082#include "Crypto.h"
Jeff Tinkercc82dc62013-02-08 10:18:35 -080083#include "Drm.h"
Andreas Huber59451f82012-09-18 10:36:32 -070084#include "HDCP.h"
Andreas Huberb7319a72013-05-29 14:20:52 -070085#include "HTTPBase.h"
Andreas Huber35213f12012-08-29 11:41:50 -070086#include "RemoteDisplay.h"
Andreas Hubered3e3e02012-03-26 11:13:27 -070087
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070088namespace {
nikoa64c8c72009-07-20 15:07:26 -070089using android::media::Metadata;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070090using android::status_t;
91using android::OK;
92using android::BAD_VALUE;
93using android::NOT_ENOUGH_DATA;
94using android::Parcel;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070095
96// Max number of entries in the filter.
97const int kMaxFilterSize = 64; // I pulled that out of thin air.
98
nikoa64c8c72009-07-20 15:07:26 -070099// FIXME: Move all the metadata related function in the Metadata.cpp
nikod608a812009-07-16 16:39:53 -0700100
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700101
102// Unmarshall a filter from a Parcel.
103// Filter format in a parcel:
104//
105// 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
106// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
107// | number of entries (n) |
108// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
109// | metadata type 1 |
110// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
111// | metadata type 2 |
112// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
113// ....
114// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
115// | metadata type n |
116// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
117//
118// @param p Parcel that should start with a filter.
119// @param[out] filter On exit contains the list of metadata type to be
120// filtered.
121// @param[out] status On exit contains the status code to be returned.
122// @return true if the parcel starts with a valid filter.
123bool unmarshallFilter(const Parcel& p,
nikoa64c8c72009-07-20 15:07:26 -0700124 Metadata::Filter *filter,
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700125 status_t *status)
126{
Nicolas Catania48290382009-07-10 13:53:06 -0700127 int32_t val;
128 if (p.readInt32(&val) != OK)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700129 {
Steve Block29357bc2012-01-06 19:20:56 +0000130 ALOGE("Failed to read filter's length");
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700131 *status = NOT_ENOUGH_DATA;
132 return false;
133 }
134
Nicolas Catania48290382009-07-10 13:53:06 -0700135 if( val > kMaxFilterSize || val < 0)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700136 {
Steve Block29357bc2012-01-06 19:20:56 +0000137 ALOGE("Invalid filter len %d", val);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700138 *status = BAD_VALUE;
139 return false;
140 }
141
Nicolas Catania48290382009-07-10 13:53:06 -0700142 const size_t num = val;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700143
144 filter->clear();
Nicolas Catania48290382009-07-10 13:53:06 -0700145 filter->setCapacity(num);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700146
nikoa64c8c72009-07-20 15:07:26 -0700147 size_t size = num * sizeof(Metadata::Type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700148
Nicolas Catania48290382009-07-10 13:53:06 -0700149
150 if (p.dataAvail() < size)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700151 {
Steve Block29357bc2012-01-06 19:20:56 +0000152 ALOGE("Filter too short expected %d but got %d", size, p.dataAvail());
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700153 *status = NOT_ENOUGH_DATA;
154 return false;
155 }
156
nikoa64c8c72009-07-20 15:07:26 -0700157 const Metadata::Type *data =
158 static_cast<const Metadata::Type*>(p.readInplace(size));
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700159
Nicolas Catania48290382009-07-10 13:53:06 -0700160 if (NULL == data)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700161 {
Steve Block29357bc2012-01-06 19:20:56 +0000162 ALOGE("Filter had no data");
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700163 *status = BAD_VALUE;
164 return false;
165 }
166
167 // TODO: The stl impl of vector would be more efficient here
168 // because it degenerates into a memcpy on pod types. Try to
169 // replace later or use stl::set.
Nicolas Catania48290382009-07-10 13:53:06 -0700170 for (size_t i = 0; i < num; ++i)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700171 {
Nicolas Catania48290382009-07-10 13:53:06 -0700172 filter->add(*data);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700173 ++data;
174 }
175 *status = OK;
176 return true;
177}
178
Nicolas Catania48290382009-07-10 13:53:06 -0700179// @param filter Of metadata type.
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700180// @param val To be searched.
181// @return true if a match was found.
nikoa64c8c72009-07-20 15:07:26 -0700182bool findMetadata(const Metadata::Filter& filter, const int32_t val)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700183{
184 // Deal with empty and ANY right away
185 if (filter.isEmpty()) return false;
nikoa64c8c72009-07-20 15:07:26 -0700186 if (filter[0] == Metadata::kAny) return true;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700187
Nicolas Catania48290382009-07-10 13:53:06 -0700188 return filter.indexOf(val) >= 0;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700189}
190
191} // anonymous namespace
192
193
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700194namespace {
195using android::Parcel;
196using android::String16;
197
198// marshalling tag indicating flattened utf16 tags
199// keep in sync with frameworks/base/media/java/android/media/AudioAttributes.java
200const int32_t kAudioAttributesMarshallTagFlattenTags = 1;
201
202// Audio attributes format in a parcel:
203//
204// 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
205// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
206// | usage |
207// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
208// | content_type |
209// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Hyejin Kim4f418f92014-09-05 15:50:03 +0900210// | source |
211// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700212// | flags |
213// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
214// | kAudioAttributesMarshallTagFlattenTags | // ignore tags if not found
215// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
216// | flattened tags in UTF16 |
217// | ... |
218// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
219//
220// @param p Parcel that contains audio attributes.
221// @param[out] attributes On exit points to an initialized audio_attributes_t structure
222// @param[out] status On exit contains the status code to be returned.
223void unmarshallAudioAttributes(const Parcel& parcel, audio_attributes_t *attributes)
224{
225 attributes->usage = (audio_usage_t) parcel.readInt32();
226 attributes->content_type = (audio_content_type_t) parcel.readInt32();
Hyejin Kim4f418f92014-09-05 15:50:03 +0900227 attributes->source = (audio_source_t) parcel.readInt32();
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700228 attributes->flags = (audio_flags_mask_t) parcel.readInt32();
229 const bool hasFlattenedTag = (parcel.readInt32() == kAudioAttributesMarshallTagFlattenTags);
230 if (hasFlattenedTag) {
231 // the tags are UTF16, convert to UTF8
232 String16 tags = parcel.readString16();
233 ssize_t realTagSize = utf16_to_utf8_length(tags.string(), tags.size());
234 if (realTagSize <= 0) {
235 strcpy(attributes->tags, "");
236 } else {
237 // copy the flattened string into the attributes as the destination for the conversion:
238 // copying array size -1, array for tags was calloc'd, no need to NULL-terminate it
239 size_t tagSize = realTagSize > AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 ?
240 AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 : realTagSize;
241 utf16_to_utf8(tags.string(), tagSize, attributes->tags);
242 }
243 } else {
244 ALOGE("unmarshallAudioAttributes() received unflattened tags, ignoring tag values");
245 strcpy(attributes->tags, "");
246 }
247}
248} // anonymous namespace
249
250
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800251namespace android {
252
Marco Nelissenf09611f2015-02-13 14:12:42 -0800253extern ALooperRoster gLooperRoster;
254
255
Dave Burked681bbb2011-08-30 14:39:17 +0100256static bool checkPermission(const char* permissionString) {
Dave Burked681bbb2011-08-30 14:39:17 +0100257 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
258 bool ok = checkCallingPermission(String16(permissionString));
Steve Block29357bc2012-01-06 19:20:56 +0000259 if (!ok) ALOGE("Request requires %s", permissionString);
Dave Burked681bbb2011-08-30 14:39:17 +0100260 return ok;
261}
262
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800263// 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 -0800264/* static */ int MediaPlayerService::AudioOutput::mMinBufferCount = 4;
265/* static */ bool MediaPlayerService::AudioOutput::mIsOnEmulator = false;
266
267void MediaPlayerService::instantiate() {
268 defaultServiceManager()->addService(
269 String16("media.player"), new MediaPlayerService());
270}
271
272MediaPlayerService::MediaPlayerService()
273{
Steve Block3856b092011-10-20 11:56:00 +0100274 ALOGV("MediaPlayerService created");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800275 mNextConnId = 1;
Gloria Wang9ee159b2011-02-24 14:51:45 -0800276
277 mBatteryAudio.refCount = 0;
278 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
279 mBatteryAudio.deviceOn[i] = 0;
280 mBatteryAudio.lastTime[i] = 0;
281 mBatteryAudio.totalTime[i] = 0;
282 }
283 // speaker is on by default
284 mBatteryAudio.deviceOn[SPEAKER] = 1;
John Grossman44a7e422012-06-21 17:29:24 -0700285
Chong Zhang0b30fd42014-07-23 14:46:05 -0700286 // reset battery stats
287 // if the mediaserver has crashed, battery stats could be left
288 // in bad state, reset the state upon service start.
Wei Jia3f273d12015-11-24 09:06:49 -0800289 BatteryNotifier::getInstance().noteResetVideo();
Chong Zhang0b30fd42014-07-23 14:46:05 -0700290
John Grossman44a7e422012-06-21 17:29:24 -0700291 MediaPlayerFactory::registerBuiltinFactories();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800292}
293
294MediaPlayerService::~MediaPlayerService()
295{
Steve Block3856b092011-10-20 11:56:00 +0100296 ALOGV("MediaPlayerService destroyed");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800297}
298
Svet Ganovbe71aa22015-04-28 12:06:02 -0700299sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(const String16 &opPackageName)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800300{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800301 pid_t pid = IPCThreadState::self()->getCallingPid();
Svet Ganovbe71aa22015-04-28 12:06:02 -0700302 sp<MediaRecorderClient> recorder = new MediaRecorderClient(this, pid, opPackageName);
Gloria Wangdac6a312009-10-29 15:46:37 -0700303 wp<MediaRecorderClient> w = recorder;
304 Mutex::Autolock lock(mLock);
305 mMediaRecorderClients.add(w);
Steve Block3856b092011-10-20 11:56:00 +0100306 ALOGV("Create new media recorder client from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800307 return recorder;
308}
309
Gloria Wangdac6a312009-10-29 15:46:37 -0700310void MediaPlayerService::removeMediaRecorderClient(wp<MediaRecorderClient> client)
311{
312 Mutex::Autolock lock(mLock);
313 mMediaRecorderClients.remove(client);
Steve Block3856b092011-10-20 11:56:00 +0100314 ALOGV("Delete media recorder client");
Gloria Wangdac6a312009-10-29 15:46:37 -0700315}
316
Glenn Kastenf37971f2012-02-03 11:06:53 -0800317sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800318{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800319 pid_t pid = IPCThreadState::self()->getCallingPid();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800320 sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
Steve Block3856b092011-10-20 11:56:00 +0100321 ALOGV("Create new media retriever from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800322 return retriever;
323}
324
Glenn Kastenf37971f2012-02-03 11:06:53 -0800325sp<IMediaPlayer> MediaPlayerService::create(const sp<IMediaPlayerClient>& client,
Dave Burked681bbb2011-08-30 14:39:17 +0100326 int audioSessionId)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800327{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800328 pid_t pid = IPCThreadState::self()->getCallingPid();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800329 int32_t connId = android_atomic_inc(&mNextConnId);
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700330
331 sp<Client> c = new Client(
332 this, pid, connId, client, audioSessionId,
333 IPCThreadState::self()->getCallingUid());
334
Steve Block3856b092011-10-20 11:56:00 +0100335 ALOGV("Create new client(%d) from pid %d, uid %d, ", connId, pid,
Dave Burked681bbb2011-08-30 14:39:17 +0100336 IPCThreadState::self()->getCallingUid());
337
338 wp<Client> w = c;
339 {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800340 Mutex::Autolock lock(mLock);
341 mClients.add(w);
342 }
Andreas Hubere2b10282010-11-23 11:41:34 -0800343 return c;
344}
345
Lajos Molnar1381d4b2014-08-07 15:18:35 -0700346sp<IMediaCodecList> MediaPlayerService::getCodecList() const {
347 return MediaCodecList::getLocalInstance();
348}
349
Andreas Huber318ad9c2009-10-15 13:46:54 -0700350sp<IOMX> MediaPlayerService::getOMX() {
351 Mutex::Autolock autoLock(mLock);
352
353 if (mOMX.get() == NULL) {
354 mOMX = new OMX;
355 }
356
357 return mOMX;
Andreas Huber20111aa2009-07-14 16:56:47 -0700358}
359
Andreas Hubered3e3e02012-03-26 11:13:27 -0700360sp<ICrypto> MediaPlayerService::makeCrypto() {
Andreas Huber1bd139a2012-04-03 14:19:20 -0700361 return new Crypto;
Andreas Hubered3e3e02012-03-26 11:13:27 -0700362}
363
Jeff Tinkercc82dc62013-02-08 10:18:35 -0800364sp<IDrm> MediaPlayerService::makeDrm() {
365 return new Drm;
366}
367
Andreas Huber279dcd82013-01-30 10:41:25 -0800368sp<IHDCP> MediaPlayerService::makeHDCP(bool createEncryptionModule) {
369 return new HDCP(createEncryptionModule);
Andreas Huber59451f82012-09-18 10:36:32 -0700370}
371
Jeff Brown2013a542012-09-04 21:38:42 -0700372sp<IRemoteDisplay> MediaPlayerService::listenForRemoteDisplay(
Svet Ganovbe71aa22015-04-28 12:06:02 -0700373 const String16 &opPackageName,
Jeff Brown2013a542012-09-04 21:38:42 -0700374 const sp<IRemoteDisplayClient>& client, const String8& iface) {
Jeff Brownaba33d52012-09-07 17:38:58 -0700375 if (!checkPermission("android.permission.CONTROL_WIFI_DISPLAY")) {
376 return NULL;
377 }
378
Svet Ganovbe71aa22015-04-28 12:06:02 -0700379 return new RemoteDisplay(opPackageName, client, iface.string());
Jeff Brown2013a542012-09-04 21:38:42 -0700380}
381
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800382status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
383{
384 const size_t SIZE = 256;
385 char buffer[SIZE];
386 String8 result;
387
388 result.append(" AudioOutput\n");
389 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n",
390 mStreamType, mLeftVolume, mRightVolume);
391 result.append(buffer);
392 snprintf(buffer, 255, " msec per frame(%f), latency (%d)\n",
Eric Laurentdb354e52012-03-05 17:27:11 -0800393 mMsecsPerFrame, (mTrack != 0) ? mTrack->latency() : -1);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800394 result.append(buffer);
Eric Laurent2beeb502010-07-16 07:43:46 -0700395 snprintf(buffer, 255, " aux effect id(%d), send level (%f)\n",
396 mAuxEffectId, mSendLevel);
397 result.append(buffer);
398
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800399 ::write(fd, result.string(), result.size());
400 if (mTrack != 0) {
401 mTrack->dump(fd, args);
402 }
403 return NO_ERROR;
404}
405
Lajos Molnar6d339f12015-04-17 16:15:53 -0700406status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800407{
408 const size_t SIZE = 256;
409 char buffer[SIZE];
410 String8 result;
411 result.append(" Client\n");
412 snprintf(buffer, 255, " pid(%d), connId(%d), status(%d), looping(%s)\n",
413 mPid, mConnId, mStatus, mLoop?"true": "false");
414 result.append(buffer);
415 write(fd, result.string(), result.size());
Andreas Hubera0b1d4b2011-06-07 15:52:25 -0700416 if (mPlayer != NULL) {
417 mPlayer->dump(fd, args);
418 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800419 if (mAudioOutput != 0) {
420 mAudioOutput->dump(fd, args);
421 }
422 write(fd, "\n", 1);
423 return NO_ERROR;
424}
425
Marco Nelissenf09611f2015-02-13 14:12:42 -0800426/**
427 * The only arguments this understands right now are -c, -von and -voff,
428 * which are parsed by ALooperRoster::dump()
429 */
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800430status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
431{
432 const size_t SIZE = 256;
433 char buffer[SIZE];
434 String8 result;
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530435 SortedVector< sp<Client> > clients; //to serialise the mutex unlock & client destruction.
436 SortedVector< sp<MediaRecorderClient> > mediaRecorderClients;
437
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800438 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
439 snprintf(buffer, SIZE, "Permission Denial: "
440 "can't dump MediaPlayerService from pid=%d, uid=%d\n",
441 IPCThreadState::self()->getCallingPid(),
442 IPCThreadState::self()->getCallingUid());
443 result.append(buffer);
444 } else {
445 Mutex::Autolock lock(mLock);
446 for (int i = 0, n = mClients.size(); i < n; ++i) {
447 sp<Client> c = mClients[i].promote();
448 if (c != 0) c->dump(fd, args);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530449 clients.add(c);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800450 }
James Dongb9141222010-07-08 11:16:11 -0700451 if (mMediaRecorderClients.size() == 0) {
452 result.append(" No media recorder client\n\n");
453 } else {
454 for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
455 sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
James Donge579e282011-10-18 22:29:20 -0700456 if (c != 0) {
457 snprintf(buffer, 255, " MediaRecorderClient pid(%d)\n", c->mPid);
458 result.append(buffer);
459 write(fd, result.string(), result.size());
460 result = "\n";
461 c->dump(fd, args);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530462 mediaRecorderClients.add(c);
James Donge579e282011-10-18 22:29:20 -0700463 }
James Dongb9141222010-07-08 11:16:11 -0700464 }
Gloria Wangdac6a312009-10-29 15:46:37 -0700465 }
466
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800467 result.append(" Files opened and/or mapped:\n");
Marco Nelissenf09611f2015-02-13 14:12:42 -0800468 snprintf(buffer, SIZE, "/proc/%d/maps", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800469 FILE *f = fopen(buffer, "r");
470 if (f) {
471 while (!feof(f)) {
472 fgets(buffer, SIZE, f);
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700473 if (strstr(buffer, " /storage/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800474 strstr(buffer, " /system/sounds/") ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700475 strstr(buffer, " /data/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800476 strstr(buffer, " /system/media/")) {
477 result.append(" ");
478 result.append(buffer);
479 }
480 }
481 fclose(f);
482 } else {
483 result.append("couldn't open ");
484 result.append(buffer);
485 result.append("\n");
486 }
487
Marco Nelissenf09611f2015-02-13 14:12:42 -0800488 snprintf(buffer, SIZE, "/proc/%d/fd", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800489 DIR *d = opendir(buffer);
490 if (d) {
491 struct dirent *ent;
492 while((ent = readdir(d)) != NULL) {
493 if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
Marco Nelissenf09611f2015-02-13 14:12:42 -0800494 snprintf(buffer, SIZE, "/proc/%d/fd/%s", getpid(), ent->d_name);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800495 struct stat s;
496 if (lstat(buffer, &s) == 0) {
497 if ((s.st_mode & S_IFMT) == S_IFLNK) {
498 char linkto[256];
499 int len = readlink(buffer, linkto, sizeof(linkto));
500 if(len > 0) {
501 if(len > 255) {
502 linkto[252] = '.';
503 linkto[253] = '.';
504 linkto[254] = '.';
505 linkto[255] = 0;
506 } else {
507 linkto[len] = 0;
508 }
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700509 if (strstr(linkto, "/storage/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800510 strstr(linkto, "/system/sounds/") == linkto ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700511 strstr(linkto, "/data/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800512 strstr(linkto, "/system/media/") == linkto) {
513 result.append(" ");
514 result.append(buffer);
515 result.append(" -> ");
516 result.append(linkto);
517 result.append("\n");
518 }
519 }
520 } else {
521 result.append(" unexpected type for ");
522 result.append(buffer);
523 result.append("\n");
524 }
525 }
526 }
527 }
528 closedir(d);
529 } else {
530 result.append("couldn't open ");
531 result.append(buffer);
532 result.append("\n");
533 }
534
Marco Nelissenf09611f2015-02-13 14:12:42 -0800535 gLooperRoster.dump(fd, args);
536
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800537 bool dumpMem = false;
538 for (size_t i = 0; i < args.size(); i++) {
539 if (args[i] == String16("-m")) {
540 dumpMem = true;
541 }
542 }
543 if (dumpMem) {
James Dong8635b7b2011-03-14 17:01:38 -0700544 dumpMemoryAddresses(fd);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800545 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800546 }
547 write(fd, result.string(), result.size());
548 return NO_ERROR;
549}
550
551void MediaPlayerService::removeClient(wp<Client> client)
552{
553 Mutex::Autolock lock(mLock);
554 mClients.remove(client);
555}
556
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700557MediaPlayerService::Client::Client(
558 const sp<MediaPlayerService>& service, pid_t pid,
559 int32_t connId, const sp<IMediaPlayerClient>& client,
560 int audioSessionId, uid_t uid)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800561{
Steve Block3856b092011-10-20 11:56:00 +0100562 ALOGV("Client(%d) constructor", connId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800563 mPid = pid;
564 mConnId = connId;
565 mService = service;
566 mClient = client;
567 mLoop = false;
568 mStatus = NO_INIT;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700569 mAudioSessionId = audioSessionId;
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700570 mUID = uid;
John Grossmanc795b642012-02-22 15:38:35 -0800571 mRetransmitEndpointValid = false;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700572 mAudioAttributes = NULL;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700573
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800574#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000575 ALOGD("create Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800576 mAntagonizer = new Antagonizer(notify, this);
577#endif
578}
579
580MediaPlayerService::Client::~Client()
581{
Steve Block3856b092011-10-20 11:56:00 +0100582 ALOGV("Client(%d) destructor pid = %d", mConnId, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800583 mAudioOutput.clear();
584 wp<Client> client(this);
585 disconnect();
586 mService->removeClient(client);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700587 if (mAudioAttributes != NULL) {
588 free(mAudioAttributes);
589 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800590}
591
592void MediaPlayerService::Client::disconnect()
593{
Steve Block3856b092011-10-20 11:56:00 +0100594 ALOGV("disconnect(%d) from pid %d", mConnId, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800595 // grab local reference and clear main reference to prevent future
596 // access to object
597 sp<MediaPlayerBase> p;
598 {
599 Mutex::Autolock l(mLock);
600 p = mPlayer;
beanzdcfefde2012-11-05 09:51:43 +0800601 mClient.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800602 }
Andreas Huber20111aa2009-07-14 16:56:47 -0700603
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800604 mPlayer.clear();
605
606 // clear the notification to prevent callbacks to dead client
607 // and reset the player. We assume the player will serialize
608 // access to itself if necessary.
609 if (p != 0) {
610 p->setNotifyCallback(0, 0);
611#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000612 ALOGD("kill Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800613 mAntagonizer->kill();
614#endif
615 p->reset();
616 }
617
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700618 disconnectNativeWindow();
619
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800620 IPCThreadState::self()->flushCommands();
621}
622
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800623sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
624{
625 // determine if we have the right player type
626 sp<MediaPlayerBase> p = mPlayer;
627 if ((p != NULL) && (p->playerType() != playerType)) {
Steve Block3856b092011-10-20 11:56:00 +0100628 ALOGV("delete player");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800629 p.clear();
630 }
631 if (p == NULL) {
Ronghua Wu68845c12015-07-21 09:50:48 -0700632 p = MediaPlayerFactory::createPlayer(playerType, this, notify, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800633 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700634
Jason Simmonsdb29e522011-08-12 13:46:55 -0700635 if (p != NULL) {
636 p->setUID(mUID);
637 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700638
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800639 return p;
640}
641
John Grossmanc795b642012-02-22 15:38:35 -0800642sp<MediaPlayerBase> MediaPlayerService::Client::setDataSource_pre(
643 player_type playerType)
644{
645 ALOGV("player type = %d", playerType);
646
647 // create the right type of player
648 sp<MediaPlayerBase> p = createPlayer(playerType);
649 if (p == NULL) {
650 return p;
651 }
652
653 if (!p->hardwareOutput()) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -0700654 Mutex::Autolock l(mLock);
Marco Nelissend457c972014-02-11 08:47:07 -0800655 mAudioOutput = new AudioOutput(mAudioSessionId, IPCThreadState::self()->getCallingUid(),
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700656 mPid, mAudioAttributes);
John Grossmanc795b642012-02-22 15:38:35 -0800657 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
658 }
659
660 return p;
661}
662
663void MediaPlayerService::Client::setDataSource_post(
664 const sp<MediaPlayerBase>& p,
665 status_t status)
666{
667 ALOGV(" setDataSource");
668 mStatus = status;
669 if (mStatus != OK) {
670 ALOGE(" error: %d", mStatus);
671 return;
672 }
673
674 // Set the re-transmission endpoint if one was chosen.
675 if (mRetransmitEndpointValid) {
676 mStatus = p->setRetransmitEndpoint(&mRetransmitEndpoint);
677 if (mStatus != NO_ERROR) {
678 ALOGE("setRetransmitEndpoint error: %d", mStatus);
679 }
680 }
681
682 if (mStatus == OK) {
683 mPlayer = p;
684 }
685}
686
Andreas Huber2db84552010-01-28 11:19:57 -0800687status_t MediaPlayerService::Client::setDataSource(
Andreas Huber1b86fe02014-01-29 11:13:26 -0800688 const sp<IMediaHTTPService> &httpService,
689 const char *url,
690 const KeyedVector<String8, String8> *headers)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800691{
Steve Block3856b092011-10-20 11:56:00 +0100692 ALOGV("setDataSource(%s)", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800693 if (url == NULL)
694 return UNKNOWN_ERROR;
695
Dave Burked681bbb2011-08-30 14:39:17 +0100696 if ((strncmp(url, "http://", 7) == 0) ||
697 (strncmp(url, "https://", 8) == 0) ||
698 (strncmp(url, "rtsp://", 7) == 0)) {
699 if (!checkPermission("android.permission.INTERNET")) {
700 return PERMISSION_DENIED;
701 }
702 }
703
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800704 if (strncmp(url, "content://", 10) == 0) {
705 // get a filedescriptor for the content Uri and
706 // pass it to the setDataSource(fd) method
707
708 String16 url16(url);
709 int fd = android::openContentProviderFile(url16);
710 if (fd < 0)
711 {
Steve Block29357bc2012-01-06 19:20:56 +0000712 ALOGE("Couldn't open fd for %s", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800713 return UNKNOWN_ERROR;
714 }
715 setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
716 close(fd);
717 return mStatus;
718 } else {
John Grossman44a7e422012-06-21 17:29:24 -0700719 player_type playerType = MediaPlayerFactory::getPlayerType(this, url);
John Grossmanc795b642012-02-22 15:38:35 -0800720 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
721 if (p == NULL) {
722 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800723 }
724
Andreas Huber1b86fe02014-01-29 11:13:26 -0800725 setDataSource_post(p, p->setDataSource(httpService, url, headers));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800726 return mStatus;
727 }
728}
729
730status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
731{
Marco Nelissen83b0fd92015-09-16 13:48:07 -0700732 ALOGV("setDataSource fd=%d (%s), offset=%lld, length=%lld",
733 fd, nameForFd(fd).c_str(), (long long) offset, (long long) length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800734 struct stat sb;
735 int ret = fstat(fd, &sb);
736 if (ret != 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000737 ALOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800738 return UNKNOWN_ERROR;
739 }
740
Ying Wang5fde15d2015-04-20 22:13:22 -0700741 ALOGV("st_dev = %llu", static_cast<uint64_t>(sb.st_dev));
Steve Block3856b092011-10-20 11:56:00 +0100742 ALOGV("st_mode = %u", sb.st_mode);
Mark Salyzyn77342f72014-06-18 16:31:32 -0700743 ALOGV("st_uid = %lu", static_cast<unsigned long>(sb.st_uid));
744 ALOGV("st_gid = %lu", static_cast<unsigned long>(sb.st_gid));
Steve Block3856b092011-10-20 11:56:00 +0100745 ALOGV("st_size = %llu", sb.st_size);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800746
747 if (offset >= sb.st_size) {
Steve Block29357bc2012-01-06 19:20:56 +0000748 ALOGE("offset error");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800749 return UNKNOWN_ERROR;
750 }
751 if (offset + length > sb.st_size) {
752 length = sb.st_size - offset;
Steve Block3856b092011-10-20 11:56:00 +0100753 ALOGV("calculated length = %lld", length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800754 }
755
John Grossman44a7e422012-06-21 17:29:24 -0700756 player_type playerType = MediaPlayerFactory::getPlayerType(this,
757 fd,
758 offset,
759 length);
John Grossmanc795b642012-02-22 15:38:35 -0800760 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
761 if (p == NULL) {
762 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800763 }
764
765 // now set data source
John Grossmanc795b642012-02-22 15:38:35 -0800766 setDataSource_post(p, p->setDataSource(fd, offset, length));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800767 return mStatus;
768}
769
Andreas Hubere2b10282010-11-23 11:41:34 -0800770status_t MediaPlayerService::Client::setDataSource(
771 const sp<IStreamSource> &source) {
772 // create the right type of player
John Grossman44a7e422012-06-21 17:29:24 -0700773 player_type playerType = MediaPlayerFactory::getPlayerType(this, source);
John Grossmanc795b642012-02-22 15:38:35 -0800774 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
Andreas Hubere2b10282010-11-23 11:41:34 -0800775 if (p == NULL) {
776 return NO_INIT;
777 }
778
Andreas Hubere2b10282010-11-23 11:41:34 -0800779 // now set data source
John Grossmanc795b642012-02-22 15:38:35 -0800780 setDataSource_post(p, p->setDataSource(source));
Andreas Hubere2b10282010-11-23 11:41:34 -0800781 return mStatus;
782}
783
Chris Watkins99f31602015-03-20 13:06:33 -0700784status_t MediaPlayerService::Client::setDataSource(
785 const sp<IDataSource> &source) {
786 sp<DataSource> dataSource = DataSource::CreateFromIDataSource(source);
787 player_type playerType = MediaPlayerFactory::getPlayerType(this, dataSource);
788 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
789 if (p == NULL) {
790 return NO_INIT;
791 }
792 // now set data source
793 setDataSource_post(p, p->setDataSource(dataSource));
794 return mStatus;
795}
796
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700797void MediaPlayerService::Client::disconnectNativeWindow() {
798 if (mConnectedWindow != NULL) {
799 status_t err = native_window_api_disconnect(mConnectedWindow.get(),
800 NATIVE_WINDOW_API_MEDIA);
801
802 if (err != OK) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000803 ALOGW("native_window_api_disconnect returned an error: %s (%d)",
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700804 strerror(-err), err);
805 }
806 }
807 mConnectedWindow.clear();
808}
809
Glenn Kasten11731182011-02-08 17:26:17 -0800810status_t MediaPlayerService::Client::setVideoSurfaceTexture(
Andy McFadden484566c2012-12-18 09:46:54 -0800811 const sp<IGraphicBufferProducer>& bufferProducer)
Glenn Kasten11731182011-02-08 17:26:17 -0800812{
Andy McFadden484566c2012-12-18 09:46:54 -0800813 ALOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, bufferProducer.get());
Glenn Kasten11731182011-02-08 17:26:17 -0800814 sp<MediaPlayerBase> p = getPlayer();
815 if (p == 0) return UNKNOWN_ERROR;
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700816
Marco Nelissenf8880202014-11-14 07:58:25 -0800817 sp<IBinder> binder(IInterface::asBinder(bufferProducer));
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700818 if (mConnectedWindowBinder == binder) {
819 return OK;
820 }
821
822 sp<ANativeWindow> anw;
Andy McFadden484566c2012-12-18 09:46:54 -0800823 if (bufferProducer != NULL) {
Marco Nelissenee08f7e2013-09-16 13:30:01 -0700824 anw = new Surface(bufferProducer, true /* controlledByApp */);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700825 status_t err = native_window_api_connect(anw.get(),
826 NATIVE_WINDOW_API_MEDIA);
827
828 if (err != OK) {
Steve Block29357bc2012-01-06 19:20:56 +0000829 ALOGE("setVideoSurfaceTexture failed: %d", err);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700830 // Note that we must do the reset before disconnecting from the ANW.
831 // Otherwise queue/dequeue calls could be made on the disconnected
832 // ANW, which may result in errors.
833 reset();
834
835 disconnectNativeWindow();
836
837 return err;
838 }
839 }
840
Andy McFadden484566c2012-12-18 09:46:54 -0800841 // Note that we must set the player's new GraphicBufferProducer before
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700842 // disconnecting the old one. Otherwise queue/dequeue calls could be made
843 // on the disconnected ANW, which may result in errors.
Andy McFadden484566c2012-12-18 09:46:54 -0800844 status_t err = p->setVideoSurfaceTexture(bufferProducer);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700845
846 disconnectNativeWindow();
847
848 mConnectedWindow = anw;
849
850 if (err == OK) {
851 mConnectedWindowBinder = binder;
852 } else {
853 disconnectNativeWindow();
854 }
855
856 return err;
Glenn Kasten11731182011-02-08 17:26:17 -0800857}
858
Nicolas Catania1d187f12009-05-12 23:25:55 -0700859status_t MediaPlayerService::Client::invoke(const Parcel& request,
860 Parcel *reply)
861{
862 sp<MediaPlayerBase> p = getPlayer();
863 if (p == NULL) return UNKNOWN_ERROR;
864 return p->invoke(request, reply);
865}
866
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700867// This call doesn't need to access the native player.
868status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
869{
870 status_t status;
nikoa64c8c72009-07-20 15:07:26 -0700871 media::Metadata::Filter allow, drop;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700872
Nicolas Catania48290382009-07-10 13:53:06 -0700873 if (unmarshallFilter(filter, &allow, &status) &&
874 unmarshallFilter(filter, &drop, &status)) {
875 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700876
877 mMetadataAllow = allow;
878 mMetadataDrop = drop;
879 }
880 return status;
881}
882
Nicolas Catania48290382009-07-10 13:53:06 -0700883status_t MediaPlayerService::Client::getMetadata(
Mark Salyzyn77342f72014-06-18 16:31:32 -0700884 bool update_only, bool /*apply_filter*/, Parcel *reply)
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700885{
nikoa64c8c72009-07-20 15:07:26 -0700886 sp<MediaPlayerBase> player = getPlayer();
887 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania48290382009-07-10 13:53:06 -0700888
nikod608a812009-07-16 16:39:53 -0700889 status_t status;
890 // Placeholder for the return code, updated by the caller.
891 reply->writeInt32(-1);
892
nikoa64c8c72009-07-20 15:07:26 -0700893 media::Metadata::Filter ids;
Nicolas Catania48290382009-07-10 13:53:06 -0700894
895 // We don't block notifications while we fetch the data. We clear
896 // mMetadataUpdated first so we don't lose notifications happening
897 // during the rest of this call.
898 {
899 Mutex::Autolock lock(mLock);
900 if (update_only) {
nikod608a812009-07-16 16:39:53 -0700901 ids = mMetadataUpdated;
Nicolas Catania48290382009-07-10 13:53:06 -0700902 }
903 mMetadataUpdated.clear();
904 }
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700905
nikoa64c8c72009-07-20 15:07:26 -0700906 media::Metadata metadata(reply);
Nicolas Catania48290382009-07-10 13:53:06 -0700907
nikoa64c8c72009-07-20 15:07:26 -0700908 metadata.appendHeader();
909 status = player->getMetadata(ids, reply);
nikod608a812009-07-16 16:39:53 -0700910
911 if (status != OK) {
nikoa64c8c72009-07-20 15:07:26 -0700912 metadata.resetParcel();
Steve Block29357bc2012-01-06 19:20:56 +0000913 ALOGE("getMetadata failed %d", status);
nikod608a812009-07-16 16:39:53 -0700914 return status;
915 }
916
917 // FIXME: Implement filtering on the result. Not critical since
918 // filtering takes place on the update notifications already. This
919 // would be when all the metadata are fetch and a filter is set.
920
nikod608a812009-07-16 16:39:53 -0700921 // Everything is fine, update the metadata length.
nikoa64c8c72009-07-20 15:07:26 -0700922 metadata.updateLength();
nikod608a812009-07-16 16:39:53 -0700923 return OK;
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700924}
925
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800926status_t MediaPlayerService::Client::prepareAsync()
927{
Steve Block3856b092011-10-20 11:56:00 +0100928 ALOGV("[%d] prepareAsync", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800929 sp<MediaPlayerBase> p = getPlayer();
930 if (p == 0) return UNKNOWN_ERROR;
931 status_t ret = p->prepareAsync();
932#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000933 ALOGD("start Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800934 if (ret == NO_ERROR) mAntagonizer->start();
935#endif
936 return ret;
937}
938
939status_t MediaPlayerService::Client::start()
940{
Steve Block3856b092011-10-20 11:56:00 +0100941 ALOGV("[%d] start", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800942 sp<MediaPlayerBase> p = getPlayer();
943 if (p == 0) return UNKNOWN_ERROR;
944 p->setLooping(mLoop);
945 return p->start();
946}
947
948status_t MediaPlayerService::Client::stop()
949{
Steve Block3856b092011-10-20 11:56:00 +0100950 ALOGV("[%d] stop", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800951 sp<MediaPlayerBase> p = getPlayer();
952 if (p == 0) return UNKNOWN_ERROR;
953 return p->stop();
954}
955
956status_t MediaPlayerService::Client::pause()
957{
Steve Block3856b092011-10-20 11:56:00 +0100958 ALOGV("[%d] pause", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800959 sp<MediaPlayerBase> p = getPlayer();
960 if (p == 0) return UNKNOWN_ERROR;
961 return p->pause();
962}
963
964status_t MediaPlayerService::Client::isPlaying(bool* state)
965{
966 *state = false;
967 sp<MediaPlayerBase> p = getPlayer();
968 if (p == 0) return UNKNOWN_ERROR;
969 *state = p->isPlaying();
Steve Block3856b092011-10-20 11:56:00 +0100970 ALOGV("[%d] isPlaying: %d", mConnId, *state);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800971 return NO_ERROR;
972}
973
Lajos Molnar3a474aa2015-04-24 17:10:07 -0700974status_t MediaPlayerService::Client::setPlaybackSettings(const AudioPlaybackRate& rate)
Wei Jia98160162015-02-04 17:01:11 -0800975{
Lajos Molnar3a474aa2015-04-24 17:10:07 -0700976 ALOGV("[%d] setPlaybackSettings(%f, %f, %d, %d)",
977 mConnId, rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Wei Jia98160162015-02-04 17:01:11 -0800978 sp<MediaPlayerBase> p = getPlayer();
979 if (p == 0) return UNKNOWN_ERROR;
Lajos Molnar3a474aa2015-04-24 17:10:07 -0700980 return p->setPlaybackSettings(rate);
981}
982
983status_t MediaPlayerService::Client::getPlaybackSettings(AudioPlaybackRate* rate /* nonnull */)
984{
985 sp<MediaPlayerBase> p = getPlayer();
986 if (p == 0) return UNKNOWN_ERROR;
987 status_t ret = p->getPlaybackSettings(rate);
988 if (ret == NO_ERROR) {
989 ALOGV("[%d] getPlaybackSettings(%f, %f, %d, %d)",
990 mConnId, rate->mSpeed, rate->mPitch, rate->mFallbackMode, rate->mStretchMode);
991 } else {
992 ALOGV("[%d] getPlaybackSettings returned %d", mConnId, ret);
993 }
994 return ret;
995}
996
997status_t MediaPlayerService::Client::setSyncSettings(
998 const AVSyncSettings& sync, float videoFpsHint)
999{
1000 ALOGV("[%d] setSyncSettings(%u, %u, %f, %f)",
1001 mConnId, sync.mSource, sync.mAudioAdjustMode, sync.mTolerance, videoFpsHint);
1002 sp<MediaPlayerBase> p = getPlayer();
1003 if (p == 0) return UNKNOWN_ERROR;
1004 return p->setSyncSettings(sync, videoFpsHint);
1005}
1006
1007status_t MediaPlayerService::Client::getSyncSettings(
1008 AVSyncSettings* sync /* nonnull */, float* videoFps /* nonnull */)
1009{
1010 sp<MediaPlayerBase> p = getPlayer();
1011 if (p == 0) return UNKNOWN_ERROR;
1012 status_t ret = p->getSyncSettings(sync, videoFps);
1013 if (ret == NO_ERROR) {
1014 ALOGV("[%d] getSyncSettings(%u, %u, %f, %f)",
1015 mConnId, sync->mSource, sync->mAudioAdjustMode, sync->mTolerance, *videoFps);
1016 } else {
1017 ALOGV("[%d] getSyncSettings returned %d", mConnId, ret);
1018 }
1019 return ret;
Wei Jia98160162015-02-04 17:01:11 -08001020}
1021
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001022status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
1023{
Steve Block3856b092011-10-20 11:56:00 +01001024 ALOGV("getCurrentPosition");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001025 sp<MediaPlayerBase> p = getPlayer();
1026 if (p == 0) return UNKNOWN_ERROR;
1027 status_t ret = p->getCurrentPosition(msec);
1028 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001029 ALOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001030 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001031 ALOGE("getCurrentPosition returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001032 }
1033 return ret;
1034}
1035
1036status_t MediaPlayerService::Client::getDuration(int *msec)
1037{
Steve Block3856b092011-10-20 11:56:00 +01001038 ALOGV("getDuration");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001039 sp<MediaPlayerBase> p = getPlayer();
1040 if (p == 0) return UNKNOWN_ERROR;
1041 status_t ret = p->getDuration(msec);
1042 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001043 ALOGV("[%d] getDuration = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001044 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001045 ALOGE("getDuration returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001046 }
1047 return ret;
1048}
1049
Marco Nelissen6b74d672012-02-28 16:07:44 -08001050status_t MediaPlayerService::Client::setNextPlayer(const sp<IMediaPlayer>& player) {
1051 ALOGV("setNextPlayer");
1052 Mutex::Autolock l(mLock);
1053 sp<Client> c = static_cast<Client*>(player.get());
1054 mNextClient = c;
John Grossman5f7e55e2012-08-24 14:47:25 -07001055
1056 if (c != NULL) {
1057 if (mAudioOutput != NULL) {
1058 mAudioOutput->setNextOutput(c->mAudioOutput);
1059 } else if ((mPlayer != NULL) && !mPlayer->hardwareOutput()) {
1060 ALOGE("no current audio output");
1061 }
1062
1063 if ((mPlayer != NULL) && (mNextClient->getPlayer() != NULL)) {
1064 mPlayer->setNextPlayer(mNextClient->getPlayer());
1065 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001066 }
John Grossman5f7e55e2012-08-24 14:47:25 -07001067
Marco Nelissen6b74d672012-02-28 16:07:44 -08001068 return OK;
1069}
1070
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001071status_t MediaPlayerService::Client::seekTo(int msec)
1072{
Steve Block3856b092011-10-20 11:56:00 +01001073 ALOGV("[%d] seekTo(%d)", mConnId, msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001074 sp<MediaPlayerBase> p = getPlayer();
1075 if (p == 0) return UNKNOWN_ERROR;
1076 return p->seekTo(msec);
1077}
1078
1079status_t MediaPlayerService::Client::reset()
1080{
Steve Block3856b092011-10-20 11:56:00 +01001081 ALOGV("[%d] reset", mConnId);
John Grossmanc795b642012-02-22 15:38:35 -08001082 mRetransmitEndpointValid = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001083 sp<MediaPlayerBase> p = getPlayer();
1084 if (p == 0) return UNKNOWN_ERROR;
1085 return p->reset();
1086}
1087
Glenn Kastenfff6d712012-01-12 16:38:12 -08001088status_t MediaPlayerService::Client::setAudioStreamType(audio_stream_type_t type)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001089{
Steve Block3856b092011-10-20 11:56:00 +01001090 ALOGV("[%d] setAudioStreamType(%d)", mConnId, type);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001091 // TODO: for hardware output, call player instead
1092 Mutex::Autolock l(mLock);
1093 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1094 return NO_ERROR;
1095}
1096
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001097status_t MediaPlayerService::Client::setAudioAttributes_l(const Parcel &parcel)
1098{
1099 if (mAudioAttributes != NULL) { free(mAudioAttributes); }
1100 mAudioAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001101 if (mAudioAttributes == NULL) {
1102 return NO_MEMORY;
1103 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001104 unmarshallAudioAttributes(parcel, mAudioAttributes);
1105
1106 ALOGV("setAudioAttributes_l() usage=%d content=%d flags=0x%x tags=%s",
1107 mAudioAttributes->usage, mAudioAttributes->content_type, mAudioAttributes->flags,
1108 mAudioAttributes->tags);
1109
1110 if (mAudioOutput != 0) {
1111 mAudioOutput->setAudioAttributes(mAudioAttributes);
1112 }
1113 return NO_ERROR;
1114}
1115
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001116status_t MediaPlayerService::Client::setLooping(int loop)
1117{
Steve Block3856b092011-10-20 11:56:00 +01001118 ALOGV("[%d] setLooping(%d)", mConnId, loop);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001119 mLoop = loop;
1120 sp<MediaPlayerBase> p = getPlayer();
1121 if (p != 0) return p->setLooping(loop);
1122 return NO_ERROR;
1123}
1124
1125status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1126{
Steve Block3856b092011-10-20 11:56:00 +01001127 ALOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
John Grossman761defc2012-02-09 15:09:05 -08001128
1129 // for hardware output, call player instead
1130 sp<MediaPlayerBase> p = getPlayer();
1131 {
1132 Mutex::Autolock l(mLock);
1133 if (p != 0 && p->hardwareOutput()) {
1134 MediaPlayerHWInterface* hwp =
1135 reinterpret_cast<MediaPlayerHWInterface*>(p.get());
1136 return hwp->setVolume(leftVolume, rightVolume);
1137 } else {
1138 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1139 return NO_ERROR;
1140 }
1141 }
1142
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001143 return NO_ERROR;
1144}
1145
Eric Laurent2beeb502010-07-16 07:43:46 -07001146status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1147{
Steve Block3856b092011-10-20 11:56:00 +01001148 ALOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
Eric Laurent2beeb502010-07-16 07:43:46 -07001149 Mutex::Autolock l(mLock);
1150 if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1151 return NO_ERROR;
1152}
1153
1154status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1155{
Steve Block3856b092011-10-20 11:56:00 +01001156 ALOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
Eric Laurent2beeb502010-07-16 07:43:46 -07001157 Mutex::Autolock l(mLock);
1158 if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1159 return NO_ERROR;
1160}
Nicolas Catania48290382009-07-10 13:53:06 -07001161
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001162status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
Steve Block3856b092011-10-20 11:56:00 +01001163 ALOGV("[%d] setParameter(%d)", mConnId, key);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001164 switch (key) {
1165 case KEY_PARAMETER_AUDIO_ATTRIBUTES:
1166 {
1167 Mutex::Autolock l(mLock);
1168 return setAudioAttributes_l(request);
1169 }
1170 default:
1171 sp<MediaPlayerBase> p = getPlayer();
1172 if (p == 0) { return UNKNOWN_ERROR; }
1173 return p->setParameter(key, request);
1174 }
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001175}
1176
1177status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
Steve Block3856b092011-10-20 11:56:00 +01001178 ALOGV("[%d] getParameter(%d)", mConnId, key);
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001179 sp<MediaPlayerBase> p = getPlayer();
1180 if (p == 0) return UNKNOWN_ERROR;
1181 return p->getParameter(key, reply);
1182}
1183
John Grossmanc795b642012-02-22 15:38:35 -08001184status_t MediaPlayerService::Client::setRetransmitEndpoint(
1185 const struct sockaddr_in* endpoint) {
1186
1187 if (NULL != endpoint) {
1188 uint32_t a = ntohl(endpoint->sin_addr.s_addr);
1189 uint16_t p = ntohs(endpoint->sin_port);
1190 ALOGV("[%d] setRetransmitEndpoint(%u.%u.%u.%u:%hu)", mConnId,
1191 (a >> 24), (a >> 16) & 0xFF, (a >> 8) & 0xFF, (a & 0xFF), p);
1192 } else {
1193 ALOGV("[%d] setRetransmitEndpoint = <none>", mConnId);
1194 }
1195
1196 sp<MediaPlayerBase> p = getPlayer();
1197
1198 // Right now, the only valid time to set a retransmit endpoint is before
1199 // player selection has been made (since the presence or absence of a
1200 // retransmit endpoint is going to determine which player is selected during
1201 // setDataSource).
1202 if (p != 0) return INVALID_OPERATION;
1203
1204 if (NULL != endpoint) {
1205 mRetransmitEndpoint = *endpoint;
1206 mRetransmitEndpointValid = true;
1207 } else {
1208 mRetransmitEndpointValid = false;
1209 }
1210
1211 return NO_ERROR;
1212}
1213
John Grossman44a7e422012-06-21 17:29:24 -07001214status_t MediaPlayerService::Client::getRetransmitEndpoint(
1215 struct sockaddr_in* endpoint)
1216{
1217 if (NULL == endpoint)
1218 return BAD_VALUE;
1219
1220 sp<MediaPlayerBase> p = getPlayer();
1221
1222 if (p != NULL)
1223 return p->getRetransmitEndpoint(endpoint);
1224
1225 if (!mRetransmitEndpointValid)
1226 return NO_INIT;
1227
1228 *endpoint = mRetransmitEndpoint;
1229
1230 return NO_ERROR;
1231}
1232
Gloria Wangb483c472011-04-11 17:23:27 -07001233void MediaPlayerService::Client::notify(
1234 void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001235{
1236 Client* client = static_cast<Client*>(cookie);
James Dongb8a98252012-08-26 16:13:03 -07001237 if (client == NULL) {
1238 return;
1239 }
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001240
James Dongb8a98252012-08-26 16:13:03 -07001241 sp<IMediaPlayerClient> c;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001242 {
1243 Mutex::Autolock l(client->mLock);
James Dongb8a98252012-08-26 16:13:03 -07001244 c = client->mClient;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001245 if (msg == MEDIA_PLAYBACK_COMPLETE && client->mNextClient != NULL) {
John Grossmancb0b7552012-08-23 17:47:31 -07001246 if (client->mAudioOutput != NULL)
1247 client->mAudioOutput->switchToNextOutput();
Marco Nelissen6b74d672012-02-28 16:07:44 -08001248 client->mNextClient->start();
1249 client->mNextClient->mClient->notify(MEDIA_INFO, MEDIA_INFO_STARTED_AS_NEXT, 0, obj);
1250 }
1251 }
1252
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001253 if (MEDIA_INFO == msg &&
Nicolas Catania48290382009-07-10 13:53:06 -07001254 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikoa64c8c72009-07-20 15:07:26 -07001255 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania48290382009-07-10 13:53:06 -07001256
1257 if(client->shouldDropMetadata(metadata_type)) {
1258 return;
1259 }
1260
1261 // Update the list of metadata that have changed. getMetadata
1262 // also access mMetadataUpdated and clears it.
1263 client->addNewMetadataUpdate(metadata_type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001264 }
James Dongb8a98252012-08-26 16:13:03 -07001265
1266 if (c != NULL) {
1267 ALOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
1268 c->notify(msg, ext1, ext2, obj);
1269 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001270}
1271
Nicolas Catania48290382009-07-10 13:53:06 -07001272
nikoa64c8c72009-07-20 15:07:26 -07001273bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001274{
Nicolas Catania48290382009-07-10 13:53:06 -07001275 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001276
Nicolas Catania48290382009-07-10 13:53:06 -07001277 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001278 return true;
1279 }
1280
Nicolas Catania48290382009-07-10 13:53:06 -07001281 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001282 return false;
Nicolas Catania48290382009-07-10 13:53:06 -07001283 } else {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001284 return true;
1285 }
1286}
1287
Nicolas Catania48290382009-07-10 13:53:06 -07001288
nikoa64c8c72009-07-20 15:07:26 -07001289void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania48290382009-07-10 13:53:06 -07001290 Mutex::Autolock lock(mLock);
1291 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1292 mMetadataUpdated.add(metadata_type);
1293 }
1294}
1295
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001296#if CALLBACK_ANTAGONIZER
1297const int Antagonizer::interval = 10000; // 10 msecs
1298
1299Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1300 mExit(false), mActive(false), mClient(client), mCb(cb)
1301{
1302 createThread(callbackThread, this);
1303}
1304
1305void Antagonizer::kill()
1306{
1307 Mutex::Autolock _l(mLock);
1308 mActive = false;
1309 mExit = true;
1310 mCondition.wait(mLock);
1311}
1312
1313int Antagonizer::callbackThread(void* user)
1314{
Steve Blockb8a80522011-12-20 16:23:08 +00001315 ALOGD("Antagonizer started");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001316 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1317 while (!p->mExit) {
1318 if (p->mActive) {
Steve Block3856b092011-10-20 11:56:00 +01001319 ALOGV("send event");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001320 p->mCb(p->mClient, 0, 0, 0);
1321 }
1322 usleep(interval);
1323 }
1324 Mutex::Autolock _l(p->mLock);
1325 p->mCondition.signal();
Steve Blockb8a80522011-12-20 16:23:08 +00001326 ALOGD("Antagonizer stopped");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001327 return 0;
1328}
1329#endif
1330
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001331#undef LOG_TAG
1332#define LOG_TAG "AudioSink"
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001333MediaPlayerService::AudioOutput::AudioOutput(int sessionId, int uid, int pid,
1334 const audio_attributes_t* attr)
Andreas Huber20111aa2009-07-14 16:56:47 -07001335 : mCallback(NULL),
Eric Laurenta514bdb2010-06-21 09:27:30 -07001336 mCallbackCookie(NULL),
Marco Nelissen6b74d672012-02-28 16:07:44 -08001337 mCallbackData(NULL),
Marco Nelissen4110c102012-03-29 09:31:28 -07001338 mBytesWritten(0),
Andy Hungd1c74342015-07-07 16:54:23 -07001339 mStreamType(AUDIO_STREAM_MUSIC),
Andy Hungd1c74342015-07-07 16:54:23 -07001340 mLeftVolume(1.0),
1341 mRightVolume(1.0),
1342 mPlaybackRate(AUDIO_PLAYBACK_RATE_DEFAULT),
1343 mSampleRateHz(0),
1344 mMsecsPerFrame(0),
1345 mFrameSize(0),
Eric Laurent1948eb32012-04-13 16:50:19 -07001346 mSessionId(sessionId),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001347 mUid(uid),
Marco Nelissend457c972014-02-11 08:47:07 -08001348 mPid(pid),
Andy Hungd1c74342015-07-07 16:54:23 -07001349 mSendLevel(0.0),
1350 mAuxEffectId(0),
1351 mFlags(AUDIO_OUTPUT_FLAG_NONE)
1352{
Steve Block3856b092011-10-20 11:56:00 +01001353 ALOGV("AudioOutput(%d)", sessionId);
Eric Laurent43562692015-07-15 16:49:07 -07001354 if (attr != NULL) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001355 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1356 if (mAttributes != NULL) {
1357 memcpy(mAttributes, attr, sizeof(audio_attributes_t));
1358 mStreamType = audio_attributes_to_stream_type(attr);
1359 }
1360 } else {
1361 mAttributes = NULL;
Eric Laurent43562692015-07-15 16:49:07 -07001362 }
1363
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001364 setMinBufferCount();
1365}
1366
1367MediaPlayerService::AudioOutput::~AudioOutput()
1368{
1369 close();
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001370 free(mAttributes);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001371 delete mCallbackData;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001372}
1373
Andy Hungd1c74342015-07-07 16:54:23 -07001374//static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001375void MediaPlayerService::AudioOutput::setMinBufferCount()
1376{
1377 char value[PROPERTY_VALUE_MAX];
1378 if (property_get("ro.kernel.qemu", value, 0)) {
1379 mIsOnEmulator = true;
1380 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1381 }
1382}
1383
Andy Hungd1c74342015-07-07 16:54:23 -07001384// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001385bool MediaPlayerService::AudioOutput::isOnEmulator()
1386{
Andy Hungd1c74342015-07-07 16:54:23 -07001387 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001388 return mIsOnEmulator;
1389}
1390
Andy Hungd1c74342015-07-07 16:54:23 -07001391// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001392int MediaPlayerService::AudioOutput::getMinBufferCount()
1393{
Andy Hungd1c74342015-07-07 16:54:23 -07001394 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001395 return mMinBufferCount;
1396}
1397
1398ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1399{
Andy Hungd1c74342015-07-07 16:54:23 -07001400 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001401 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001402 return mTrack->frameCount() * mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001403}
1404
1405ssize_t MediaPlayerService::AudioOutput::frameCount() const
1406{
Andy Hungd1c74342015-07-07 16:54:23 -07001407 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001408 if (mTrack == 0) return NO_INIT;
1409 return mTrack->frameCount();
1410}
1411
1412ssize_t MediaPlayerService::AudioOutput::channelCount() const
1413{
Andy Hungd1c74342015-07-07 16:54:23 -07001414 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001415 if (mTrack == 0) return NO_INIT;
1416 return mTrack->channelCount();
1417}
1418
1419ssize_t MediaPlayerService::AudioOutput::frameSize() const
1420{
Andy Hungd1c74342015-07-07 16:54:23 -07001421 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001422 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001423 return mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001424}
1425
1426uint32_t MediaPlayerService::AudioOutput::latency () const
1427{
Andy Hungd1c74342015-07-07 16:54:23 -07001428 Mutex::Autolock lock(mLock);
Eric Laurentdb354e52012-03-05 17:27:11 -08001429 if (mTrack == 0) return 0;
1430 return mTrack->latency();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001431}
1432
1433float MediaPlayerService::AudioOutput::msecsPerFrame() const
1434{
Andy Hungd1c74342015-07-07 16:54:23 -07001435 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001436 return mMsecsPerFrame;
1437}
1438
Marco Nelissen4110c102012-03-29 09:31:28 -07001439status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position) const
Eric Laurent342e9cf2010-01-19 17:37:09 -08001440{
Andy Hungd1c74342015-07-07 16:54:23 -07001441 Mutex::Autolock lock(mLock);
Eric Laurent342e9cf2010-01-19 17:37:09 -08001442 if (mTrack == 0) return NO_INIT;
1443 return mTrack->getPosition(position);
1444}
1445
Lajos Molnar06ad1522014-08-28 07:27:44 -07001446status_t MediaPlayerService::AudioOutput::getTimestamp(AudioTimestamp &ts) const
1447{
Andy Hungd1c74342015-07-07 16:54:23 -07001448 Mutex::Autolock lock(mLock);
Lajos Molnar06ad1522014-08-28 07:27:44 -07001449 if (mTrack == 0) return NO_INIT;
1450 return mTrack->getTimestamp(ts);
1451}
1452
Wei Jiac4ac8172015-10-21 10:35:48 -07001453// TODO: Remove unnecessary calls to getPlayedOutDurationUs()
1454// as it acquires locks and may query the audio driver.
1455//
1456// Some calls could conceivably retrieve extrapolated data instead of
1457// accessing getTimestamp() or getPosition() every time a data buffer with
1458// a media time is received.
1459//
1460// Calculate duration of played samples if played at normal rate (i.e., 1.0).
1461int64_t MediaPlayerService::AudioOutput::getPlayedOutDurationUs(int64_t nowUs) const
1462{
1463 Mutex::Autolock lock(mLock);
1464 if (mTrack == 0 || mSampleRateHz == 0) {
Wei Jia213f4902015-10-22 08:55:25 -07001465 return 0;
Wei Jiac4ac8172015-10-21 10:35:48 -07001466 }
1467
1468 uint32_t numFramesPlayed;
1469 int64_t numFramesPlayedAt;
1470 AudioTimestamp ts;
1471 static const int64_t kStaleTimestamp100ms = 100000;
1472
1473 status_t res = mTrack->getTimestamp(ts);
1474 if (res == OK) { // case 1: mixing audio tracks and offloaded tracks.
1475 numFramesPlayed = ts.mPosition;
1476 numFramesPlayedAt = ts.mTime.tv_sec * 1000000LL + ts.mTime.tv_nsec / 1000;
1477 const int64_t timestampAge = nowUs - numFramesPlayedAt;
1478 if (timestampAge > kStaleTimestamp100ms) {
1479 // This is an audio FIXME.
1480 // getTimestamp returns a timestamp which may come from audio mixing threads.
1481 // After pausing, the MixerThread may go idle, thus the mTime estimate may
1482 // become stale. Assuming that the MixerThread runs 20ms, with FastMixer at 5ms,
1483 // the max latency should be about 25ms with an average around 12ms (to be verified).
1484 // For safety we use 100ms.
1485 ALOGV("getTimestamp: returned stale timestamp nowUs(%lld) numFramesPlayedAt(%lld)",
1486 (long long)nowUs, (long long)numFramesPlayedAt);
1487 numFramesPlayedAt = nowUs - kStaleTimestamp100ms;
1488 }
1489 //ALOGD("getTimestamp: OK %d %lld", numFramesPlayed, (long long)numFramesPlayedAt);
1490 } else if (res == WOULD_BLOCK) { // case 2: transitory state on start of a new track
1491 numFramesPlayed = 0;
1492 numFramesPlayedAt = nowUs;
1493 //ALOGD("getTimestamp: WOULD_BLOCK %d %lld",
1494 // numFramesPlayed, (long long)numFramesPlayedAt);
1495 } else { // case 3: transitory at new track or audio fast tracks.
1496 res = mTrack->getPosition(&numFramesPlayed);
1497 CHECK_EQ(res, (status_t)OK);
1498 numFramesPlayedAt = nowUs;
1499 numFramesPlayedAt += 1000LL * mTrack->latency() / 2; /* XXX */
1500 //ALOGD("getPosition: %u %lld", numFramesPlayed, (long long)numFramesPlayedAt);
1501 }
1502
1503 // CHECK_EQ(numFramesPlayed & (1 << 31), 0); // can't be negative until 12.4 hrs, test
1504 // TODO: remove the (int32_t) casting below as it may overflow at 12.4 hours.
1505 int64_t durationUs = (int64_t)((int32_t)numFramesPlayed * 1000000LL / mSampleRateHz)
1506 + nowUs - numFramesPlayedAt;
1507 if (durationUs < 0) {
1508 // Occurs when numFramesPlayed position is very small and the following:
1509 // (1) In case 1, the time nowUs is computed before getTimestamp() is called and
1510 // numFramesPlayedAt is greater than nowUs by time more than numFramesPlayed.
1511 // (2) In case 3, using getPosition and adding mAudioSink->latency() to
1512 // numFramesPlayedAt, by a time amount greater than numFramesPlayed.
1513 //
1514 // Both of these are transitory conditions.
1515 ALOGV("getPlayedOutDurationUs: negative duration %lld set to zero", (long long)durationUs);
1516 durationUs = 0;
1517 }
1518 ALOGV("getPlayedOutDurationUs(%lld) nowUs(%lld) frames(%u) framesAt(%lld)",
1519 (long long)durationUs, (long long)nowUs, numFramesPlayed, (long long)numFramesPlayedAt);
1520 return durationUs;
1521}
1522
Marco Nelissen4110c102012-03-29 09:31:28 -07001523status_t MediaPlayerService::AudioOutput::getFramesWritten(uint32_t *frameswritten) const
1524{
Andy Hungd1c74342015-07-07 16:54:23 -07001525 Mutex::Autolock lock(mLock);
Marco Nelissen4110c102012-03-29 09:31:28 -07001526 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001527 *frameswritten = mBytesWritten / mFrameSize;
Marco Nelissen4110c102012-03-29 09:31:28 -07001528 return OK;
1529}
1530
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001531status_t MediaPlayerService::AudioOutput::setParameters(const String8& keyValuePairs)
1532{
Andy Hungd1c74342015-07-07 16:54:23 -07001533 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001534 if (mTrack == 0) return NO_INIT;
1535 return mTrack->setParameters(keyValuePairs);
1536}
1537
1538String8 MediaPlayerService::AudioOutput::getParameters(const String8& keys)
1539{
Andy Hungd1c74342015-07-07 16:54:23 -07001540 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001541 if (mTrack == 0) return String8::empty();
1542 return mTrack->getParameters(keys);
1543}
1544
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001545void MediaPlayerService::AudioOutput::setAudioAttributes(const audio_attributes_t * attributes) {
Andy Hungd1c74342015-07-07 16:54:23 -07001546 Mutex::Autolock lock(mLock);
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001547 if (attributes == NULL) {
1548 free(mAttributes);
1549 mAttributes = NULL;
1550 } else {
1551 if (mAttributes == NULL) {
1552 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1553 }
1554 memcpy(mAttributes, attributes, sizeof(audio_attributes_t));
Eric Laurent43562692015-07-15 16:49:07 -07001555 mStreamType = audio_attributes_to_stream_type(attributes);
1556 }
1557}
1558
1559void MediaPlayerService::AudioOutput::setAudioStreamType(audio_stream_type_t streamType)
1560{
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001561 Mutex::Autolock lock(mLock);
Eric Laurent43562692015-07-15 16:49:07 -07001562 // do not allow direct stream type modification if attributes have been set
1563 if (mAttributes == NULL) {
1564 mStreamType = streamType;
1565 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001566}
1567
Andy Hungd1c74342015-07-07 16:54:23 -07001568void MediaPlayerService::AudioOutput::deleteRecycledTrack_l()
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001569{
Andy Hungd1c74342015-07-07 16:54:23 -07001570 ALOGV("deleteRecycledTrack_l");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001571 if (mRecycledTrack != 0) {
1572
1573 if (mCallbackData != NULL) {
1574 mCallbackData->setOutput(NULL);
1575 mCallbackData->endTrackSwitch();
1576 }
1577
1578 if ((mRecycledTrack->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) {
1579 mRecycledTrack->flush();
1580 }
1581 // An offloaded track isn't flushed because the STREAM_END is reported
1582 // slightly prematurely to allow time for the gapless track switch
1583 // but this means that if we decide not to recycle the track there
1584 // could be a small amount of residual data still playing. We leave
1585 // AudioFlinger to drain the track.
1586
1587 mRecycledTrack.clear();
Andy Hungd1c74342015-07-07 16:54:23 -07001588 close_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001589 delete mCallbackData;
1590 mCallbackData = NULL;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001591 }
1592}
1593
Andy Hungd1c74342015-07-07 16:54:23 -07001594void MediaPlayerService::AudioOutput::close_l()
1595{
1596 mTrack.clear();
1597}
1598
Andreas Huber20111aa2009-07-14 16:56:47 -07001599status_t MediaPlayerService::AudioOutput::open(
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001600 uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
1601 audio_format_t format, int bufferCount,
Eric Laurent1948eb32012-04-13 16:50:19 -07001602 AudioCallback cb, void *cookie,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001603 audio_output_flags_t flags,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001604 const audio_offload_info_t *offloadInfo,
Andy Hung179652e2015-05-31 22:49:46 -07001605 bool doNotReconnect,
1606 uint32_t suggestedFrameCount)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001607{
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001608 ALOGV("open(%u, %d, 0x%x, 0x%x, %d, %d 0x%x)", sampleRate, channelCount, channelMask,
1609 format, bufferCount, mSessionId, flags);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001610
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001611 // offloading is only supported in callback mode for now.
1612 // offloadInfo must be present if offload flag is set
1613 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) &&
1614 ((cb == NULL) || (offloadInfo == NULL))) {
1615 return BAD_VALUE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001616 }
1617
Andy Hung179652e2015-05-31 22:49:46 -07001618 // compute frame count for the AudioTrack internal buffer
1619 size_t frameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001620 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1621 frameCount = 0; // AudioTrack will get frame count from AudioFlinger
1622 } else {
Andy Hung179652e2015-05-31 22:49:46 -07001623 // try to estimate the buffer processing fetch size from AudioFlinger.
1624 // framesPerBuffer is approximate and generally correct, except when it's not :-).
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001625 uint32_t afSampleRate;
1626 size_t afFrameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001627 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1628 return NO_INIT;
1629 }
1630 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1631 return NO_INIT;
1632 }
Andy Hung179652e2015-05-31 22:49:46 -07001633 const size_t framesPerBuffer =
1634 (unsigned long long)sampleRate * afFrameCount / afSampleRate;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001635
Andy Hung179652e2015-05-31 22:49:46 -07001636 if (bufferCount == 0) {
1637 // use suggestedFrameCount
1638 bufferCount = (suggestedFrameCount + framesPerBuffer - 1) / framesPerBuffer;
1639 }
1640 // Check argument bufferCount against the mininum buffer count
1641 if (bufferCount != 0 && bufferCount < mMinBufferCount) {
1642 ALOGV("bufferCount (%d) increased to %d", bufferCount, mMinBufferCount);
1643 bufferCount = mMinBufferCount;
1644 }
1645 // if frameCount is 0, then AudioTrack will get frame count from AudioFlinger
1646 // which will be the minimum size permitted.
1647 frameCount = bufferCount * framesPerBuffer;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001648 }
Andreas Huber20111aa2009-07-14 16:56:47 -07001649
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001650 if (channelMask == CHANNEL_MASK_USE_CHANNEL_ORDER) {
Glenn Kastenab334fd2012-03-14 12:56:06 -07001651 channelMask = audio_channel_out_mask_from_count(channelCount);
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001652 if (0 == channelMask) {
1653 ALOGE("open() error, can\'t derive mask for %d audio channels", channelCount);
1654 return NO_INIT;
1655 }
1656 }
Eric Laurent1948eb32012-04-13 16:50:19 -07001657
Andy Hungd1c74342015-07-07 16:54:23 -07001658 Mutex::Autolock lock(mLock);
Andy Hung179652e2015-05-31 22:49:46 -07001659 mCallback = cb;
1660 mCallbackCookie = cookie;
1661
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001662 // Check whether we can recycle the track
1663 bool reuse = false;
1664 bool bothOffloaded = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001665
Glenn Kasten2799d742013-05-30 14:33:29 -07001666 if (mRecycledTrack != 0) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001667 // check whether we are switching between two offloaded tracks
1668 bothOffloaded = (flags & mRecycledTrack->getFlags()
1669 & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0;
Marco Nelissen67295b52012-06-11 14:52:53 -07001670
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001671 // check if the existing track can be reused as-is, or if a new track needs to be created.
1672 reuse = true;
1673
Marco Nelissen67295b52012-06-11 14:52:53 -07001674 if ((mCallbackData == NULL && mCallback != NULL) ||
1675 (mCallbackData != NULL && mCallback == NULL)) {
1676 // recycled track uses callbacks but the caller wants to use writes, or vice versa
1677 ALOGV("can't chain callback and write");
1678 reuse = false;
1679 } else if ((mRecycledTrack->getSampleRate() != sampleRate) ||
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001680 (mRecycledTrack->channelCount() != (uint32_t)channelCount) ) {
1681 ALOGV("samplerate, channelcount differ: %u/%u Hz, %u/%d ch",
Marco Nelissen67295b52012-06-11 14:52:53 -07001682 mRecycledTrack->getSampleRate(), sampleRate,
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001683 mRecycledTrack->channelCount(), channelCount);
Marco Nelissen67295b52012-06-11 14:52:53 -07001684 reuse = false;
1685 } else if (flags != mFlags) {
1686 ALOGV("output flags differ %08x/%08x", flags, mFlags);
1687 reuse = false;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001688 } else if (mRecycledTrack->format() != format) {
1689 reuse = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001690 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001691 } else {
1692 ALOGV("no track available to recycle");
1693 }
1694
1695 ALOGV_IF(bothOffloaded, "both tracks offloaded");
1696
1697 // If we can't recycle and both tracks are offloaded
1698 // we must close the previous output before opening a new one
1699 if (bothOffloaded && !reuse) {
1700 ALOGV("both offloaded and not recycling");
Andy Hungd1c74342015-07-07 16:54:23 -07001701 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001702 }
1703
1704 sp<AudioTrack> t;
1705 CallbackData *newcbd = NULL;
1706
1707 // We don't attempt to create a new track if we are recycling an
1708 // offloaded track. But, if we are recycling a non-offloaded or we
1709 // are switching where one is offloaded and one isn't then we create
1710 // the new track in advance so that we can read additional stream info
1711
1712 if (!(reuse && bothOffloaded)) {
1713 ALOGV("creating new AudioTrack");
1714
1715 if (mCallback != NULL) {
1716 newcbd = new CallbackData(this);
1717 t = new AudioTrack(
1718 mStreamType,
1719 sampleRate,
1720 format,
1721 channelMask,
1722 frameCount,
1723 flags,
1724 CallbackWrapper,
1725 newcbd,
1726 0, // notification frames
1727 mSessionId,
1728 AudioTrack::TRANSFER_CALLBACK,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001729 offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -08001730 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001731 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001732 mAttributes,
1733 doNotReconnect);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001734 } else {
1735 t = new AudioTrack(
1736 mStreamType,
1737 sampleRate,
1738 format,
1739 channelMask,
1740 frameCount,
1741 flags,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001742 NULL, // callback
1743 NULL, // user data
1744 0, // notification frames
1745 mSessionId,
1746 AudioTrack::TRANSFER_DEFAULT,
1747 NULL, // offload info
Marco Nelissend457c972014-02-11 08:47:07 -08001748 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001749 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001750 mAttributes,
1751 doNotReconnect);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001752 }
1753
1754 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1755 ALOGE("Unable to create audio track");
1756 delete newcbd;
Glenn Kasten3e98ecd2015-05-18 13:13:24 -07001757 // t goes out of scope, so reference count drops to zero
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001758 return NO_INIT;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001759 } else {
1760 // successful AudioTrack initialization implies a legacy stream type was generated
1761 // from the audio attributes
1762 mStreamType = t->streamType();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001763 }
1764 }
1765
1766 if (reuse) {
1767 CHECK(mRecycledTrack != NULL);
1768
1769 if (!bothOffloaded) {
1770 if (mRecycledTrack->frameCount() != t->frameCount()) {
1771 ALOGV("framecount differs: %u/%u frames",
1772 mRecycledTrack->frameCount(), t->frameCount());
1773 reuse = false;
1774 }
1775 }
1776
Marco Nelissen67295b52012-06-11 14:52:53 -07001777 if (reuse) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001778 ALOGV("chaining to next output and recycling track");
Andy Hungd1c74342015-07-07 16:54:23 -07001779 close_l();
Marco Nelissen67295b52012-06-11 14:52:53 -07001780 mTrack = mRecycledTrack;
Glenn Kasten2799d742013-05-30 14:33:29 -07001781 mRecycledTrack.clear();
Marco Nelissen67295b52012-06-11 14:52:53 -07001782 if (mCallbackData != NULL) {
1783 mCallbackData->setOutput(this);
1784 }
Marco Nelissen67295b52012-06-11 14:52:53 -07001785 delete newcbd;
1786 return OK;
1787 }
Marco Nelissen67295b52012-06-11 14:52:53 -07001788 }
1789
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001790 // we're not going to reuse the track, unblock and flush it
1791 // this was done earlier if both tracks are offloaded
1792 if (!bothOffloaded) {
Andy Hungd1c74342015-07-07 16:54:23 -07001793 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001794 }
1795
1796 CHECK((t != NULL) && ((mCallback == NULL) || (newcbd != NULL)));
1797
Marco Nelissen67295b52012-06-11 14:52:53 -07001798 mCallbackData = newcbd;
Steve Block3856b092011-10-20 11:56:00 +01001799 ALOGV("setVolume");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001800 t->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07001801
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001802 mSampleRateHz = sampleRate;
Preetam Singh Ranawat2e17eef2015-08-12 12:11:46 -07001803 mFlags = flags;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001804 mMsecsPerFrame = 1E3f / (mPlaybackRate.mSpeed * sampleRate);
Andy Hungd1c74342015-07-07 16:54:23 -07001805 mFrameSize = t->frameSize();
Marco Nelissen99448602012-04-02 12:16:49 -07001806 uint32_t pos;
1807 if (t->getPosition(&pos) == OK) {
Andy Hungd1c74342015-07-07 16:54:23 -07001808 mBytesWritten = uint64_t(pos) * mFrameSize;
Marco Nelissen99448602012-04-02 12:16:49 -07001809 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001810 mTrack = t;
Eric Laurent2beeb502010-07-16 07:43:46 -07001811
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001812 status_t res = NO_ERROR;
Wei Jia0162d002015-06-09 11:59:33 -07001813 // Note some output devices may give us a direct track even though we don't specify it.
1814 // Example: Line application b/17459982.
Preetam Singh Ranawat2e17eef2015-08-12 12:11:46 -07001815 if ((t->getFlags() & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) {
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001816 res = t->setPlaybackRate(mPlaybackRate);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001817 if (res == NO_ERROR) {
1818 t->setAuxEffectSendLevel(mSendLevel);
1819 res = t->attachAuxEffect(mAuxEffectId);
1820 }
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001821 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001822 ALOGV("open() DONE status %d", res);
1823 return res;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001824}
1825
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001826status_t MediaPlayerService::AudioOutput::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001827{
Steve Block3856b092011-10-20 11:56:00 +01001828 ALOGV("start");
Andy Hungd1c74342015-07-07 16:54:23 -07001829 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001830 if (mCallbackData != NULL) {
1831 mCallbackData->endTrackSwitch();
1832 }
Glenn Kasten2799d742013-05-30 14:33:29 -07001833 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001834 mTrack->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07001835 mTrack->setAuxEffectSendLevel(mSendLevel);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001836 return mTrack->start();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001837 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001838 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001839}
1840
Marco Nelissen6b74d672012-02-28 16:07:44 -08001841void MediaPlayerService::AudioOutput::setNextOutput(const sp<AudioOutput>& nextOutput) {
Andy Hungd1c74342015-07-07 16:54:23 -07001842 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001843 mNextOutput = nextOutput;
1844}
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08001845
Marco Nelissen6b74d672012-02-28 16:07:44 -08001846void MediaPlayerService::AudioOutput::switchToNextOutput() {
1847 ALOGV("switchToNextOutput");
Andy Hungd1c74342015-07-07 16:54:23 -07001848
1849 // Try to acquire the callback lock before moving track (without incurring deadlock).
1850 const unsigned kMaxSwitchTries = 100;
1851 Mutex::Autolock lock(mLock);
1852 for (unsigned tries = 0;;) {
1853 if (mTrack == 0) {
1854 return;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001855 }
Andy Hungd1c74342015-07-07 16:54:23 -07001856 if (mNextOutput != NULL && mNextOutput != this) {
1857 if (mCallbackData != NULL) {
1858 // two alternative approaches
1859#if 1
1860 CallbackData *callbackData = mCallbackData;
1861 mLock.unlock();
1862 // proper acquisition sequence
1863 callbackData->lock();
1864 mLock.lock();
1865 // Caution: it is unlikely that someone deleted our callback or changed our target
1866 if (callbackData != mCallbackData || mNextOutput == NULL || mNextOutput == this) {
1867 // fatal if we are starved out.
1868 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
1869 "switchToNextOutput() cannot obtain correct lock sequence");
1870 callbackData->unlock();
1871 continue;
1872 }
1873 callbackData->mSwitching = true; // begin track switch
1874#else
1875 // tryBeginTrackSwitch() returns false if the callback has the lock.
1876 if (!mCallbackData->tryBeginTrackSwitch()) {
1877 // fatal if we are starved out.
1878 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
1879 "switchToNextOutput() cannot obtain callback lock");
1880 mLock.unlock();
1881 usleep(5 * 1000 /* usec */); // allow callback to use AudioOutput
1882 mLock.lock();
1883 continue;
1884 }
1885#endif
1886 }
1887
1888 Mutex::Autolock nextLock(mNextOutput->mLock);
1889
1890 // If the next output track is not NULL, then it has been
1891 // opened already for playback.
1892 // This is possible even without the next player being started,
1893 // for example, the next player could be prepared and seeked.
1894 //
1895 // Presuming it isn't advisable to force the track over.
1896 if (mNextOutput->mTrack == NULL) {
1897 ALOGD("Recycling track for gapless playback");
1898 delete mNextOutput->mCallbackData;
1899 mNextOutput->mCallbackData = mCallbackData;
1900 mNextOutput->mRecycledTrack = mTrack;
1901 mNextOutput->mSampleRateHz = mSampleRateHz;
1902 mNextOutput->mMsecsPerFrame = mMsecsPerFrame;
1903 mNextOutput->mBytesWritten = mBytesWritten;
1904 mNextOutput->mFlags = mFlags;
1905 mNextOutput->mFrameSize = mFrameSize;
1906 close_l();
1907 mCallbackData = NULL; // destruction handled by mNextOutput
1908 } else {
1909 ALOGW("Ignoring gapless playback because next player has already started");
1910 // remove track in case resource needed for future players.
1911 if (mCallbackData != NULL) {
1912 mCallbackData->endTrackSwitch(); // release lock for callbacks before close.
1913 }
1914 close_l();
1915 }
1916 }
1917 break;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001918 }
1919}
1920
Wei Jia7d3f4df2015-03-03 15:28:00 -08001921ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001922{
Andy Hungd1c74342015-07-07 16:54:23 -07001923 Mutex::Autolock lock(mLock);
Glenn Kastenadad3d72014-02-21 14:51:43 -08001924 LOG_ALWAYS_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
Andreas Huber20111aa2009-07-14 16:56:47 -07001925
Steve Block3856b092011-10-20 11:56:00 +01001926 //ALOGV("write(%p, %u)", buffer, size);
Glenn Kasten2799d742013-05-30 14:33:29 -07001927 if (mTrack != 0) {
Wei Jia7d3f4df2015-03-03 15:28:00 -08001928 ssize_t ret = mTrack->write(buffer, size, blocking);
Andy Hunga31335a2014-08-20 17:37:59 -07001929 if (ret >= 0) {
1930 mBytesWritten += ret;
1931 }
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001932 return ret;
1933 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001934 return NO_INIT;
1935}
1936
1937void MediaPlayerService::AudioOutput::stop()
1938{
Steve Block3856b092011-10-20 11:56:00 +01001939 ALOGV("stop");
Andy Hungd1c74342015-07-07 16:54:23 -07001940 Mutex::Autolock lock(mLock);
Andy Hungda17c042015-06-01 15:53:14 -07001941 mBytesWritten = 0;
Glenn Kasten2799d742013-05-30 14:33:29 -07001942 if (mTrack != 0) mTrack->stop();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001943}
1944
1945void MediaPlayerService::AudioOutput::flush()
1946{
Steve Block3856b092011-10-20 11:56:00 +01001947 ALOGV("flush");
Andy Hungd1c74342015-07-07 16:54:23 -07001948 Mutex::Autolock lock(mLock);
Andy Hungda17c042015-06-01 15:53:14 -07001949 mBytesWritten = 0;
Glenn Kasten2799d742013-05-30 14:33:29 -07001950 if (mTrack != 0) mTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001951}
1952
1953void MediaPlayerService::AudioOutput::pause()
1954{
Steve Block3856b092011-10-20 11:56:00 +01001955 ALOGV("pause");
Andy Hungd1c74342015-07-07 16:54:23 -07001956 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07001957 if (mTrack != 0) mTrack->pause();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001958}
1959
1960void MediaPlayerService::AudioOutput::close()
1961{
Steve Block3856b092011-10-20 11:56:00 +01001962 ALOGV("close");
Erik Wolsheimer7845a1f2015-10-30 12:07:52 -07001963 sp<AudioTrack> track;
1964 {
1965 Mutex::Autolock lock(mLock);
1966 track = mTrack;
1967 close_l(); // clears mTrack
1968 }
1969 // destruction of the track occurs outside of mutex.
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001970}
1971
1972void MediaPlayerService::AudioOutput::setVolume(float left, float right)
1973{
Steve Block3856b092011-10-20 11:56:00 +01001974 ALOGV("setVolume(%f, %f)", left, right);
Andy Hungd1c74342015-07-07 16:54:23 -07001975 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001976 mLeftVolume = left;
1977 mRightVolume = right;
Glenn Kasten2799d742013-05-30 14:33:29 -07001978 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001979 mTrack->setVolume(left, right);
1980 }
1981}
1982
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001983status_t MediaPlayerService::AudioOutput::setPlaybackRate(const AudioPlaybackRate &rate)
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001984{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001985 ALOGV("setPlaybackRate(%f %f %d %d)",
1986 rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Andy Hungd1c74342015-07-07 16:54:23 -07001987 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001988 if (mTrack == 0) {
1989 // remember rate so that we can set it when the track is opened
1990 mPlaybackRate = rate;
1991 return OK;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001992 }
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001993 status_t res = mTrack->setPlaybackRate(rate);
1994 if (res != NO_ERROR) {
1995 return res;
1996 }
1997 // rate.mSpeed is always greater than 0 if setPlaybackRate succeeded
1998 CHECK_GT(rate.mSpeed, 0.f);
1999 mPlaybackRate = rate;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002000 if (mSampleRateHz != 0) {
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002001 mMsecsPerFrame = 1E3f / (rate.mSpeed * mSampleRateHz);
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002002 }
2003 return res;
2004}
2005
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002006status_t MediaPlayerService::AudioOutput::getPlaybackRate(AudioPlaybackRate *rate)
2007{
2008 ALOGV("setPlaybackRate");
Andy Hungd1c74342015-07-07 16:54:23 -07002009 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002010 if (mTrack == 0) {
2011 return NO_INIT;
2012 }
2013 *rate = mTrack->getPlaybackRate();
2014 return NO_ERROR;
2015}
2016
Eric Laurent2beeb502010-07-16 07:43:46 -07002017status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
2018{
Steve Block3856b092011-10-20 11:56:00 +01002019 ALOGV("setAuxEffectSendLevel(%f)", level);
Andy Hungd1c74342015-07-07 16:54:23 -07002020 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002021 mSendLevel = level;
Glenn Kasten2799d742013-05-30 14:33:29 -07002022 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002023 return mTrack->setAuxEffectSendLevel(level);
2024 }
2025 return NO_ERROR;
2026}
2027
2028status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
2029{
Steve Block3856b092011-10-20 11:56:00 +01002030 ALOGV("attachAuxEffect(%d)", effectId);
Andy Hungd1c74342015-07-07 16:54:23 -07002031 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002032 mAuxEffectId = effectId;
Glenn Kasten2799d742013-05-30 14:33:29 -07002033 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002034 return mTrack->attachAuxEffect(effectId);
2035 }
2036 return NO_ERROR;
2037}
2038
Andreas Huber20111aa2009-07-14 16:56:47 -07002039// static
2040void MediaPlayerService::AudioOutput::CallbackWrapper(
Glenn Kastend217a8c2011-06-01 15:20:35 -07002041 int event, void *cookie, void *info) {
Steve Block3856b092011-10-20 11:56:00 +01002042 //ALOGV("callbackwrapper");
Marco Nelissen6b74d672012-02-28 16:07:44 -08002043 CallbackData *data = (CallbackData*)cookie;
Andy Hungd1c74342015-07-07 16:54:23 -07002044 // lock to ensure we aren't caught in the middle of a track switch.
Marco Nelissen6b74d672012-02-28 16:07:44 -08002045 data->lock();
2046 AudioOutput *me = data->getOutput();
Andreas Huber20111aa2009-07-14 16:56:47 -07002047 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002048 if (me == NULL) {
2049 // no output set, likely because the track was scheduled to be reused
2050 // by another player, but the format turned out to be incompatible.
2051 data->unlock();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002052 if (buffer != NULL) {
2053 buffer->size = 0;
2054 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08002055 return;
2056 }
Andreas Huber20111aa2009-07-14 16:56:47 -07002057
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002058 switch(event) {
2059 case AudioTrack::EVENT_MORE_DATA: {
2060 size_t actualSize = (*me->mCallback)(
2061 me, buffer->raw, buffer->size, me->mCallbackCookie,
2062 CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002063
Andy Hung719b46b2015-05-31 22:18:25 -07002064 // Log when no data is returned from the callback.
2065 // (1) We may have no data (especially with network streaming sources).
2066 // (2) We may have reached the EOS and the audio track is not stopped yet.
2067 // Note that AwesomePlayer/AudioPlayer will only return zero size when it reaches the EOS.
2068 // NuPlayerRenderer will return zero when it doesn't have data (it doesn't block to fill).
2069 //
2070 // This is a benign busy-wait, with the next data request generated 10 ms or more later;
2071 // nevertheless for power reasons, we don't want to see too many of these.
Andreas Huber2e8ffaf2010-02-18 16:45:13 -08002072
Andy Hung719b46b2015-05-31 22:18:25 -07002073 ALOGV_IF(actualSize == 0 && buffer->size > 0, "callbackwrapper: empty buffer returned");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002074
Andy Hung719b46b2015-05-31 22:18:25 -07002075 me->mBytesWritten += actualSize; // benign race with reader.
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002076 buffer->size = actualSize;
2077 } break;
2078
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002079 case AudioTrack::EVENT_STREAM_END:
Andy Hung719b46b2015-05-31 22:18:25 -07002080 // currently only occurs for offloaded callbacks
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002081 ALOGV("callbackwrapper: deliver EVENT_STREAM_END");
2082 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2083 me->mCallbackCookie, CB_EVENT_STREAM_END);
2084 break;
2085
2086 case AudioTrack::EVENT_NEW_IAUDIOTRACK :
2087 ALOGV("callbackwrapper: deliver EVENT_TEAR_DOWN");
2088 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2089 me->mCallbackCookie, CB_EVENT_TEAR_DOWN);
2090 break;
2091
Glenn Kasten421743b2015-06-01 08:18:08 -07002092 case AudioTrack::EVENT_UNDERRUN:
Andy Hung719b46b2015-05-31 22:18:25 -07002093 // This occurs when there is no data available, typically
Glenn Kasten421743b2015-06-01 08:18:08 -07002094 // when there is a failure to supply data to the AudioTrack. It can also
2095 // occur in non-offloaded mode when the audio device comes out of standby.
2096 //
Andy Hung719b46b2015-05-31 22:18:25 -07002097 // If an AudioTrack underruns it outputs silence. Since this happens suddenly
2098 // it may sound like an audible pop or glitch.
2099 //
2100 // The underrun event is sent once per track underrun; the condition is reset
2101 // when more data is sent to the AudioTrack.
Glenn Kasten421743b2015-06-01 08:18:08 -07002102 ALOGI("callbackwrapper: EVENT_UNDERRUN (discarded)");
2103 break;
2104
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002105 default:
2106 ALOGE("received unknown event type: %d inside CallbackWrapper !", event);
Andreas Huber51c1e0e2011-04-04 11:43:40 -07002107 }
2108
Marco Nelissen6b74d672012-02-28 16:07:44 -08002109 data->unlock();
Andreas Huber20111aa2009-07-14 16:56:47 -07002110}
2111
Marco Nelissen4110c102012-03-29 09:31:28 -07002112int MediaPlayerService::AudioOutput::getSessionId() const
Eric Laurent8c563ed2010-10-07 18:23:03 -07002113{
Andy Hungd1c74342015-07-07 16:54:23 -07002114 Mutex::Autolock lock(mLock);
Eric Laurent8c563ed2010-10-07 18:23:03 -07002115 return mSessionId;
2116}
2117
Eric Laurent6f59db12013-07-26 17:16:50 -07002118uint32_t MediaPlayerService::AudioOutput::getSampleRate() const
2119{
Andy Hungd1c74342015-07-07 16:54:23 -07002120 Mutex::Autolock lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -07002121 if (mTrack == 0) return 0;
2122 return mTrack->getSampleRate();
2123}
2124
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002125////////////////////////////////////////////////////////////////////////////////
2126
2127struct CallbackThread : public Thread {
2128 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
2129 MediaPlayerBase::AudioSink::AudioCallback cb,
2130 void *cookie);
2131
2132protected:
2133 virtual ~CallbackThread();
2134
2135 virtual bool threadLoop();
2136
2137private:
2138 wp<MediaPlayerBase::AudioSink> mSink;
2139 MediaPlayerBase::AudioSink::AudioCallback mCallback;
2140 void *mCookie;
2141 void *mBuffer;
2142 size_t mBufferSize;
2143
2144 CallbackThread(const CallbackThread &);
2145 CallbackThread &operator=(const CallbackThread &);
2146};
2147
2148CallbackThread::CallbackThread(
2149 const wp<MediaPlayerBase::AudioSink> &sink,
2150 MediaPlayerBase::AudioSink::AudioCallback cb,
2151 void *cookie)
2152 : mSink(sink),
2153 mCallback(cb),
2154 mCookie(cookie),
2155 mBuffer(NULL),
2156 mBufferSize(0) {
2157}
2158
2159CallbackThread::~CallbackThread() {
2160 if (mBuffer) {
2161 free(mBuffer);
2162 mBuffer = NULL;
2163 }
2164}
2165
2166bool CallbackThread::threadLoop() {
2167 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
2168 if (sink == NULL) {
2169 return false;
2170 }
2171
2172 if (mBuffer == NULL) {
2173 mBufferSize = sink->bufferSize();
2174 mBuffer = malloc(mBufferSize);
2175 }
2176
2177 size_t actualSize =
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002178 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie,
2179 MediaPlayerBase::AudioSink::CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002180
2181 if (actualSize > 0) {
2182 sink->write(mBuffer, actualSize);
Andy Hunga31335a2014-08-20 17:37:59 -07002183 // Could return false on sink->write() error or short count.
2184 // Not necessarily appropriate but would work for AudioCache behavior.
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002185 }
2186
2187 return true;
2188}
2189
2190////////////////////////////////////////////////////////////////////////////////
2191
Gloria Wang7cf180c2011-02-19 18:37:57 -08002192void MediaPlayerService::addBatteryData(uint32_t params)
2193{
2194 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002195
2196 int32_t time = systemTime() / 1000000L;
2197
2198 // change audio output devices. This notification comes from AudioFlinger
2199 if ((params & kBatteryDataSpeakerOn)
2200 || (params & kBatteryDataOtherAudioDeviceOn)) {
2201
2202 int deviceOn[NUM_AUDIO_DEVICES];
2203 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2204 deviceOn[i] = 0;
2205 }
2206
2207 if ((params & kBatteryDataSpeakerOn)
2208 && (params & kBatteryDataOtherAudioDeviceOn)) {
2209 deviceOn[SPEAKER_AND_OTHER] = 1;
2210 } else if (params & kBatteryDataSpeakerOn) {
2211 deviceOn[SPEAKER] = 1;
2212 } else {
2213 deviceOn[OTHER_AUDIO_DEVICE] = 1;
2214 }
2215
2216 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2217 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
2218
2219 if (mBatteryAudio.refCount > 0) { // if playing audio
2220 if (!deviceOn[i]) {
2221 mBatteryAudio.lastTime[i] += time;
2222 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2223 mBatteryAudio.lastTime[i] = 0;
2224 } else {
2225 mBatteryAudio.lastTime[i] = 0 - time;
2226 }
2227 }
2228
2229 mBatteryAudio.deviceOn[i] = deviceOn[i];
2230 }
2231 }
2232 return;
2233 }
2234
Marco Nelissenb7848f12014-12-04 08:57:56 -08002235 // an audio stream is started
Gloria Wang9ee159b2011-02-24 14:51:45 -08002236 if (params & kBatteryDataAudioFlingerStart) {
2237 // record the start time only if currently no other audio
2238 // is being played
2239 if (mBatteryAudio.refCount == 0) {
2240 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2241 if (mBatteryAudio.deviceOn[i]) {
2242 mBatteryAudio.lastTime[i] -= time;
2243 }
2244 }
2245 }
2246
2247 mBatteryAudio.refCount ++;
2248 return;
2249
2250 } else if (params & kBatteryDataAudioFlingerStop) {
2251 if (mBatteryAudio.refCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002252 ALOGW("Battery track warning: refCount is <= 0");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002253 return;
2254 }
2255
2256 // record the stop time only if currently this is the only
2257 // audio being played
2258 if (mBatteryAudio.refCount == 1) {
2259 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2260 if (mBatteryAudio.deviceOn[i]) {
2261 mBatteryAudio.lastTime[i] += time;
2262 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2263 mBatteryAudio.lastTime[i] = 0;
2264 }
2265 }
2266 }
2267
2268 mBatteryAudio.refCount --;
2269 return;
2270 }
2271
Gloria Wang7cf180c2011-02-19 18:37:57 -08002272 int uid = IPCThreadState::self()->getCallingUid();
2273 if (uid == AID_MEDIA) {
2274 return;
2275 }
2276 int index = mBatteryData.indexOfKey(uid);
Gloria Wang7cf180c2011-02-19 18:37:57 -08002277
2278 if (index < 0) { // create a new entry for this UID
2279 BatteryUsageInfo info;
2280 info.audioTotalTime = 0;
2281 info.videoTotalTime = 0;
2282 info.audioLastTime = 0;
2283 info.videoLastTime = 0;
2284 info.refCount = 0;
2285
Gloria Wang9ee159b2011-02-24 14:51:45 -08002286 if (mBatteryData.add(uid, info) == NO_MEMORY) {
Steve Block29357bc2012-01-06 19:20:56 +00002287 ALOGE("Battery track error: no memory for new app");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002288 return;
2289 }
Gloria Wang7cf180c2011-02-19 18:37:57 -08002290 }
2291
2292 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
2293
2294 if (params & kBatteryDataCodecStarted) {
2295 if (params & kBatteryDataTrackAudio) {
2296 info.audioLastTime -= time;
2297 info.refCount ++;
2298 }
2299 if (params & kBatteryDataTrackVideo) {
2300 info.videoLastTime -= time;
2301 info.refCount ++;
2302 }
2303 } else {
2304 if (info.refCount == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002305 ALOGW("Battery track warning: refCount is already 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002306 return;
2307 } else if (info.refCount < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00002308 ALOGE("Battery track error: refCount < 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002309 mBatteryData.removeItem(uid);
2310 return;
2311 }
2312
2313 if (params & kBatteryDataTrackAudio) {
2314 info.audioLastTime += time;
2315 info.refCount --;
2316 }
2317 if (params & kBatteryDataTrackVideo) {
2318 info.videoLastTime += time;
2319 info.refCount --;
2320 }
2321
2322 // no stream is being played by this UID
2323 if (info.refCount == 0) {
2324 info.audioTotalTime += info.audioLastTime;
2325 info.audioLastTime = 0;
2326 info.videoTotalTime += info.videoLastTime;
2327 info.videoLastTime = 0;
2328 }
2329 }
2330}
2331
2332status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
2333 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002334
2335 // audio output devices usage
2336 int32_t time = systemTime() / 1000000L; //in ms
2337 int32_t totalTime;
2338
2339 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2340 totalTime = mBatteryAudio.totalTime[i];
2341
2342 if (mBatteryAudio.deviceOn[i]
2343 && (mBatteryAudio.lastTime[i] != 0)) {
2344 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
2345 totalTime += tmpTime;
2346 }
2347
2348 reply->writeInt32(totalTime);
2349 // reset the total time
2350 mBatteryAudio.totalTime[i] = 0;
2351 }
2352
2353 // codec usage
Gloria Wang7cf180c2011-02-19 18:37:57 -08002354 BatteryUsageInfo info;
2355 int size = mBatteryData.size();
2356
2357 reply->writeInt32(size);
2358 int i = 0;
2359
2360 while (i < size) {
2361 info = mBatteryData.valueAt(i);
2362
2363 reply->writeInt32(mBatteryData.keyAt(i)); //UID
2364 reply->writeInt32(info.audioTotalTime);
2365 reply->writeInt32(info.videoTotalTime);
2366
2367 info.audioTotalTime = 0;
2368 info.videoTotalTime = 0;
2369
2370 // remove the UID entry where no stream is being played
2371 if (info.refCount <= 0) {
2372 mBatteryData.removeItemsAt(i);
2373 size --;
2374 i --;
2375 }
2376 i++;
2377 }
2378 return NO_ERROR;
2379}
nikoa64c8c72009-07-20 15:07:26 -07002380} // namespace android