blob: dda0a570f5c787c4e1ea13ce998606ea3f05bd96 [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
Marco Nelissen260e56c2016-01-28 21:41:25 +0000350sp<IOMX> MediaPlayerService::getOMX() {
351 Mutex::Autolock autoLock(mLock);
352
353 if (mOMX.get() == NULL) {
354 mOMX = new OMX;
355 }
356
357 return mOMX;
358}
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();
Wei Jia2afac0c2016-01-07 12:13:07 -08001249 if (client->mNextClient->mClient != NULL) {
1250 client->mNextClient->mClient->notify(
1251 MEDIA_INFO, MEDIA_INFO_STARTED_AS_NEXT, 0, obj);
1252 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001253 }
1254 }
1255
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001256 if (MEDIA_INFO == msg &&
Nicolas Catania48290382009-07-10 13:53:06 -07001257 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikoa64c8c72009-07-20 15:07:26 -07001258 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania48290382009-07-10 13:53:06 -07001259
1260 if(client->shouldDropMetadata(metadata_type)) {
1261 return;
1262 }
1263
1264 // Update the list of metadata that have changed. getMetadata
1265 // also access mMetadataUpdated and clears it.
1266 client->addNewMetadataUpdate(metadata_type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001267 }
James Dongb8a98252012-08-26 16:13:03 -07001268
1269 if (c != NULL) {
1270 ALOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
1271 c->notify(msg, ext1, ext2, obj);
1272 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001273}
1274
Nicolas Catania48290382009-07-10 13:53:06 -07001275
nikoa64c8c72009-07-20 15:07:26 -07001276bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001277{
Nicolas Catania48290382009-07-10 13:53:06 -07001278 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001279
Nicolas Catania48290382009-07-10 13:53:06 -07001280 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001281 return true;
1282 }
1283
Nicolas Catania48290382009-07-10 13:53:06 -07001284 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001285 return false;
Nicolas Catania48290382009-07-10 13:53:06 -07001286 } else {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001287 return true;
1288 }
1289}
1290
Nicolas Catania48290382009-07-10 13:53:06 -07001291
nikoa64c8c72009-07-20 15:07:26 -07001292void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania48290382009-07-10 13:53:06 -07001293 Mutex::Autolock lock(mLock);
1294 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1295 mMetadataUpdated.add(metadata_type);
1296 }
1297}
1298
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001299#if CALLBACK_ANTAGONIZER
1300const int Antagonizer::interval = 10000; // 10 msecs
1301
1302Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1303 mExit(false), mActive(false), mClient(client), mCb(cb)
1304{
1305 createThread(callbackThread, this);
1306}
1307
1308void Antagonizer::kill()
1309{
1310 Mutex::Autolock _l(mLock);
1311 mActive = false;
1312 mExit = true;
1313 mCondition.wait(mLock);
1314}
1315
1316int Antagonizer::callbackThread(void* user)
1317{
Steve Blockb8a80522011-12-20 16:23:08 +00001318 ALOGD("Antagonizer started");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001319 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1320 while (!p->mExit) {
1321 if (p->mActive) {
Steve Block3856b092011-10-20 11:56:00 +01001322 ALOGV("send event");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001323 p->mCb(p->mClient, 0, 0, 0);
1324 }
1325 usleep(interval);
1326 }
1327 Mutex::Autolock _l(p->mLock);
1328 p->mCondition.signal();
Steve Blockb8a80522011-12-20 16:23:08 +00001329 ALOGD("Antagonizer stopped");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001330 return 0;
1331}
1332#endif
1333
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001334#undef LOG_TAG
1335#define LOG_TAG "AudioSink"
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001336MediaPlayerService::AudioOutput::AudioOutput(int sessionId, int uid, int pid,
1337 const audio_attributes_t* attr)
Andreas Huber20111aa2009-07-14 16:56:47 -07001338 : mCallback(NULL),
Eric Laurenta514bdb2010-06-21 09:27:30 -07001339 mCallbackCookie(NULL),
Marco Nelissen6b74d672012-02-28 16:07:44 -08001340 mCallbackData(NULL),
Marco Nelissen4110c102012-03-29 09:31:28 -07001341 mBytesWritten(0),
Andy Hungd1c74342015-07-07 16:54:23 -07001342 mStreamType(AUDIO_STREAM_MUSIC),
Andy Hungd1c74342015-07-07 16:54:23 -07001343 mLeftVolume(1.0),
1344 mRightVolume(1.0),
1345 mPlaybackRate(AUDIO_PLAYBACK_RATE_DEFAULT),
1346 mSampleRateHz(0),
1347 mMsecsPerFrame(0),
1348 mFrameSize(0),
Eric Laurent1948eb32012-04-13 16:50:19 -07001349 mSessionId(sessionId),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001350 mUid(uid),
Marco Nelissend457c972014-02-11 08:47:07 -08001351 mPid(pid),
Andy Hungd1c74342015-07-07 16:54:23 -07001352 mSendLevel(0.0),
1353 mAuxEffectId(0),
1354 mFlags(AUDIO_OUTPUT_FLAG_NONE)
1355{
Steve Block3856b092011-10-20 11:56:00 +01001356 ALOGV("AudioOutput(%d)", sessionId);
Eric Laurent43562692015-07-15 16:49:07 -07001357 if (attr != NULL) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001358 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1359 if (mAttributes != NULL) {
1360 memcpy(mAttributes, attr, sizeof(audio_attributes_t));
1361 mStreamType = audio_attributes_to_stream_type(attr);
1362 }
1363 } else {
1364 mAttributes = NULL;
Eric Laurent43562692015-07-15 16:49:07 -07001365 }
1366
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001367 setMinBufferCount();
1368}
1369
1370MediaPlayerService::AudioOutput::~AudioOutput()
1371{
1372 close();
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001373 free(mAttributes);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001374 delete mCallbackData;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001375}
1376
Andy Hungd1c74342015-07-07 16:54:23 -07001377//static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001378void MediaPlayerService::AudioOutput::setMinBufferCount()
1379{
1380 char value[PROPERTY_VALUE_MAX];
1381 if (property_get("ro.kernel.qemu", value, 0)) {
1382 mIsOnEmulator = true;
1383 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1384 }
1385}
1386
Andy Hungd1c74342015-07-07 16:54:23 -07001387// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001388bool MediaPlayerService::AudioOutput::isOnEmulator()
1389{
Andy Hungd1c74342015-07-07 16:54:23 -07001390 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001391 return mIsOnEmulator;
1392}
1393
Andy Hungd1c74342015-07-07 16:54:23 -07001394// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001395int MediaPlayerService::AudioOutput::getMinBufferCount()
1396{
Andy Hungd1c74342015-07-07 16:54:23 -07001397 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001398 return mMinBufferCount;
1399}
1400
1401ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1402{
Andy Hungd1c74342015-07-07 16:54:23 -07001403 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001404 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001405 return mTrack->frameCount() * mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001406}
1407
1408ssize_t MediaPlayerService::AudioOutput::frameCount() const
1409{
Andy Hungd1c74342015-07-07 16:54:23 -07001410 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001411 if (mTrack == 0) return NO_INIT;
1412 return mTrack->frameCount();
1413}
1414
1415ssize_t MediaPlayerService::AudioOutput::channelCount() const
1416{
Andy Hungd1c74342015-07-07 16:54:23 -07001417 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001418 if (mTrack == 0) return NO_INIT;
1419 return mTrack->channelCount();
1420}
1421
1422ssize_t MediaPlayerService::AudioOutput::frameSize() const
1423{
Andy Hungd1c74342015-07-07 16:54:23 -07001424 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001425 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001426 return mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001427}
1428
1429uint32_t MediaPlayerService::AudioOutput::latency () const
1430{
Andy Hungd1c74342015-07-07 16:54:23 -07001431 Mutex::Autolock lock(mLock);
Eric Laurentdb354e52012-03-05 17:27:11 -08001432 if (mTrack == 0) return 0;
1433 return mTrack->latency();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001434}
1435
1436float MediaPlayerService::AudioOutput::msecsPerFrame() const
1437{
Andy Hungd1c74342015-07-07 16:54:23 -07001438 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001439 return mMsecsPerFrame;
1440}
1441
Marco Nelissen4110c102012-03-29 09:31:28 -07001442status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position) const
Eric Laurent342e9cf2010-01-19 17:37:09 -08001443{
Andy Hungd1c74342015-07-07 16:54:23 -07001444 Mutex::Autolock lock(mLock);
Eric Laurent342e9cf2010-01-19 17:37:09 -08001445 if (mTrack == 0) return NO_INIT;
1446 return mTrack->getPosition(position);
1447}
1448
Lajos Molnar06ad1522014-08-28 07:27:44 -07001449status_t MediaPlayerService::AudioOutput::getTimestamp(AudioTimestamp &ts) const
1450{
Andy Hungd1c74342015-07-07 16:54:23 -07001451 Mutex::Autolock lock(mLock);
Lajos Molnar06ad1522014-08-28 07:27:44 -07001452 if (mTrack == 0) return NO_INIT;
1453 return mTrack->getTimestamp(ts);
1454}
1455
Wei Jiac4ac8172015-10-21 10:35:48 -07001456// TODO: Remove unnecessary calls to getPlayedOutDurationUs()
1457// as it acquires locks and may query the audio driver.
1458//
1459// Some calls could conceivably retrieve extrapolated data instead of
1460// accessing getTimestamp() or getPosition() every time a data buffer with
1461// a media time is received.
1462//
1463// Calculate duration of played samples if played at normal rate (i.e., 1.0).
1464int64_t MediaPlayerService::AudioOutput::getPlayedOutDurationUs(int64_t nowUs) const
1465{
1466 Mutex::Autolock lock(mLock);
1467 if (mTrack == 0 || mSampleRateHz == 0) {
Wei Jia213f4902015-10-22 08:55:25 -07001468 return 0;
Wei Jiac4ac8172015-10-21 10:35:48 -07001469 }
1470
1471 uint32_t numFramesPlayed;
1472 int64_t numFramesPlayedAt;
1473 AudioTimestamp ts;
1474 static const int64_t kStaleTimestamp100ms = 100000;
1475
1476 status_t res = mTrack->getTimestamp(ts);
1477 if (res == OK) { // case 1: mixing audio tracks and offloaded tracks.
1478 numFramesPlayed = ts.mPosition;
1479 numFramesPlayedAt = ts.mTime.tv_sec * 1000000LL + ts.mTime.tv_nsec / 1000;
1480 const int64_t timestampAge = nowUs - numFramesPlayedAt;
1481 if (timestampAge > kStaleTimestamp100ms) {
1482 // This is an audio FIXME.
1483 // getTimestamp returns a timestamp which may come from audio mixing threads.
1484 // After pausing, the MixerThread may go idle, thus the mTime estimate may
1485 // become stale. Assuming that the MixerThread runs 20ms, with FastMixer at 5ms,
1486 // the max latency should be about 25ms with an average around 12ms (to be verified).
1487 // For safety we use 100ms.
1488 ALOGV("getTimestamp: returned stale timestamp nowUs(%lld) numFramesPlayedAt(%lld)",
1489 (long long)nowUs, (long long)numFramesPlayedAt);
1490 numFramesPlayedAt = nowUs - kStaleTimestamp100ms;
1491 }
1492 //ALOGD("getTimestamp: OK %d %lld", numFramesPlayed, (long long)numFramesPlayedAt);
1493 } else if (res == WOULD_BLOCK) { // case 2: transitory state on start of a new track
1494 numFramesPlayed = 0;
1495 numFramesPlayedAt = nowUs;
1496 //ALOGD("getTimestamp: WOULD_BLOCK %d %lld",
1497 // numFramesPlayed, (long long)numFramesPlayedAt);
1498 } else { // case 3: transitory at new track or audio fast tracks.
1499 res = mTrack->getPosition(&numFramesPlayed);
1500 CHECK_EQ(res, (status_t)OK);
1501 numFramesPlayedAt = nowUs;
1502 numFramesPlayedAt += 1000LL * mTrack->latency() / 2; /* XXX */
1503 //ALOGD("getPosition: %u %lld", numFramesPlayed, (long long)numFramesPlayedAt);
1504 }
1505
1506 // CHECK_EQ(numFramesPlayed & (1 << 31), 0); // can't be negative until 12.4 hrs, test
1507 // TODO: remove the (int32_t) casting below as it may overflow at 12.4 hours.
1508 int64_t durationUs = (int64_t)((int32_t)numFramesPlayed * 1000000LL / mSampleRateHz)
1509 + nowUs - numFramesPlayedAt;
1510 if (durationUs < 0) {
1511 // Occurs when numFramesPlayed position is very small and the following:
1512 // (1) In case 1, the time nowUs is computed before getTimestamp() is called and
1513 // numFramesPlayedAt is greater than nowUs by time more than numFramesPlayed.
1514 // (2) In case 3, using getPosition and adding mAudioSink->latency() to
1515 // numFramesPlayedAt, by a time amount greater than numFramesPlayed.
1516 //
1517 // Both of these are transitory conditions.
1518 ALOGV("getPlayedOutDurationUs: negative duration %lld set to zero", (long long)durationUs);
1519 durationUs = 0;
1520 }
1521 ALOGV("getPlayedOutDurationUs(%lld) nowUs(%lld) frames(%u) framesAt(%lld)",
1522 (long long)durationUs, (long long)nowUs, numFramesPlayed, (long long)numFramesPlayedAt);
1523 return durationUs;
1524}
1525
Marco Nelissen4110c102012-03-29 09:31:28 -07001526status_t MediaPlayerService::AudioOutput::getFramesWritten(uint32_t *frameswritten) const
1527{
Andy Hungd1c74342015-07-07 16:54:23 -07001528 Mutex::Autolock lock(mLock);
Marco Nelissen4110c102012-03-29 09:31:28 -07001529 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001530 *frameswritten = mBytesWritten / mFrameSize;
Marco Nelissen4110c102012-03-29 09:31:28 -07001531 return OK;
1532}
1533
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001534status_t MediaPlayerService::AudioOutput::setParameters(const String8& keyValuePairs)
1535{
Andy Hungd1c74342015-07-07 16:54:23 -07001536 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001537 if (mTrack == 0) return NO_INIT;
1538 return mTrack->setParameters(keyValuePairs);
1539}
1540
1541String8 MediaPlayerService::AudioOutput::getParameters(const String8& keys)
1542{
Andy Hungd1c74342015-07-07 16:54:23 -07001543 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001544 if (mTrack == 0) return String8::empty();
1545 return mTrack->getParameters(keys);
1546}
1547
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001548void MediaPlayerService::AudioOutput::setAudioAttributes(const audio_attributes_t * attributes) {
Andy Hungd1c74342015-07-07 16:54:23 -07001549 Mutex::Autolock lock(mLock);
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001550 if (attributes == NULL) {
1551 free(mAttributes);
1552 mAttributes = NULL;
1553 } else {
1554 if (mAttributes == NULL) {
1555 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1556 }
1557 memcpy(mAttributes, attributes, sizeof(audio_attributes_t));
Eric Laurent43562692015-07-15 16:49:07 -07001558 mStreamType = audio_attributes_to_stream_type(attributes);
1559 }
1560}
1561
1562void MediaPlayerService::AudioOutput::setAudioStreamType(audio_stream_type_t streamType)
1563{
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001564 Mutex::Autolock lock(mLock);
Eric Laurent43562692015-07-15 16:49:07 -07001565 // do not allow direct stream type modification if attributes have been set
1566 if (mAttributes == NULL) {
1567 mStreamType = streamType;
1568 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001569}
1570
Andy Hungd1c74342015-07-07 16:54:23 -07001571void MediaPlayerService::AudioOutput::deleteRecycledTrack_l()
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001572{
Andy Hungd1c74342015-07-07 16:54:23 -07001573 ALOGV("deleteRecycledTrack_l");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001574 if (mRecycledTrack != 0) {
1575
1576 if (mCallbackData != NULL) {
1577 mCallbackData->setOutput(NULL);
1578 mCallbackData->endTrackSwitch();
1579 }
1580
1581 if ((mRecycledTrack->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) {
1582 mRecycledTrack->flush();
1583 }
1584 // An offloaded track isn't flushed because the STREAM_END is reported
1585 // slightly prematurely to allow time for the gapless track switch
1586 // but this means that if we decide not to recycle the track there
1587 // could be a small amount of residual data still playing. We leave
1588 // AudioFlinger to drain the track.
1589
1590 mRecycledTrack.clear();
Andy Hungd1c74342015-07-07 16:54:23 -07001591 close_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001592 delete mCallbackData;
1593 mCallbackData = NULL;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001594 }
1595}
1596
Andy Hungd1c74342015-07-07 16:54:23 -07001597void MediaPlayerService::AudioOutput::close_l()
1598{
1599 mTrack.clear();
1600}
1601
Andreas Huber20111aa2009-07-14 16:56:47 -07001602status_t MediaPlayerService::AudioOutput::open(
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001603 uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
1604 audio_format_t format, int bufferCount,
Eric Laurent1948eb32012-04-13 16:50:19 -07001605 AudioCallback cb, void *cookie,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001606 audio_output_flags_t flags,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001607 const audio_offload_info_t *offloadInfo,
Andy Hung179652e2015-05-31 22:49:46 -07001608 bool doNotReconnect,
1609 uint32_t suggestedFrameCount)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001610{
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001611 ALOGV("open(%u, %d, 0x%x, 0x%x, %d, %d 0x%x)", sampleRate, channelCount, channelMask,
1612 format, bufferCount, mSessionId, flags);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001613
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001614 // offloading is only supported in callback mode for now.
1615 // offloadInfo must be present if offload flag is set
1616 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) &&
1617 ((cb == NULL) || (offloadInfo == NULL))) {
1618 return BAD_VALUE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001619 }
1620
Andy Hung179652e2015-05-31 22:49:46 -07001621 // compute frame count for the AudioTrack internal buffer
1622 size_t frameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001623 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1624 frameCount = 0; // AudioTrack will get frame count from AudioFlinger
1625 } else {
Andy Hung179652e2015-05-31 22:49:46 -07001626 // try to estimate the buffer processing fetch size from AudioFlinger.
1627 // framesPerBuffer is approximate and generally correct, except when it's not :-).
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001628 uint32_t afSampleRate;
1629 size_t afFrameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001630 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1631 return NO_INIT;
1632 }
1633 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1634 return NO_INIT;
1635 }
Andy Hung179652e2015-05-31 22:49:46 -07001636 const size_t framesPerBuffer =
1637 (unsigned long long)sampleRate * afFrameCount / afSampleRate;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001638
Andy Hung179652e2015-05-31 22:49:46 -07001639 if (bufferCount == 0) {
1640 // use suggestedFrameCount
1641 bufferCount = (suggestedFrameCount + framesPerBuffer - 1) / framesPerBuffer;
1642 }
1643 // Check argument bufferCount against the mininum buffer count
1644 if (bufferCount != 0 && bufferCount < mMinBufferCount) {
1645 ALOGV("bufferCount (%d) increased to %d", bufferCount, mMinBufferCount);
1646 bufferCount = mMinBufferCount;
1647 }
1648 // if frameCount is 0, then AudioTrack will get frame count from AudioFlinger
1649 // which will be the minimum size permitted.
1650 frameCount = bufferCount * framesPerBuffer;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001651 }
Andreas Huber20111aa2009-07-14 16:56:47 -07001652
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001653 if (channelMask == CHANNEL_MASK_USE_CHANNEL_ORDER) {
Glenn Kastenab334fd2012-03-14 12:56:06 -07001654 channelMask = audio_channel_out_mask_from_count(channelCount);
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001655 if (0 == channelMask) {
1656 ALOGE("open() error, can\'t derive mask for %d audio channels", channelCount);
1657 return NO_INIT;
1658 }
1659 }
Eric Laurent1948eb32012-04-13 16:50:19 -07001660
Andy Hungd1c74342015-07-07 16:54:23 -07001661 Mutex::Autolock lock(mLock);
Andy Hung179652e2015-05-31 22:49:46 -07001662 mCallback = cb;
1663 mCallbackCookie = cookie;
1664
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001665 // Check whether we can recycle the track
1666 bool reuse = false;
1667 bool bothOffloaded = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001668
Glenn Kasten2799d742013-05-30 14:33:29 -07001669 if (mRecycledTrack != 0) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001670 // check whether we are switching between two offloaded tracks
1671 bothOffloaded = (flags & mRecycledTrack->getFlags()
1672 & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0;
Marco Nelissen67295b52012-06-11 14:52:53 -07001673
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001674 // check if the existing track can be reused as-is, or if a new track needs to be created.
1675 reuse = true;
1676
Marco Nelissen67295b52012-06-11 14:52:53 -07001677 if ((mCallbackData == NULL && mCallback != NULL) ||
1678 (mCallbackData != NULL && mCallback == NULL)) {
1679 // recycled track uses callbacks but the caller wants to use writes, or vice versa
1680 ALOGV("can't chain callback and write");
1681 reuse = false;
1682 } else if ((mRecycledTrack->getSampleRate() != sampleRate) ||
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001683 (mRecycledTrack->channelCount() != (uint32_t)channelCount) ) {
1684 ALOGV("samplerate, channelcount differ: %u/%u Hz, %u/%d ch",
Marco Nelissen67295b52012-06-11 14:52:53 -07001685 mRecycledTrack->getSampleRate(), sampleRate,
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001686 mRecycledTrack->channelCount(), channelCount);
Marco Nelissen67295b52012-06-11 14:52:53 -07001687 reuse = false;
1688 } else if (flags != mFlags) {
1689 ALOGV("output flags differ %08x/%08x", flags, mFlags);
1690 reuse = false;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001691 } else if (mRecycledTrack->format() != format) {
1692 reuse = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001693 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001694 } else {
1695 ALOGV("no track available to recycle");
1696 }
1697
1698 ALOGV_IF(bothOffloaded, "both tracks offloaded");
1699
1700 // If we can't recycle and both tracks are offloaded
1701 // we must close the previous output before opening a new one
1702 if (bothOffloaded && !reuse) {
1703 ALOGV("both offloaded and not recycling");
Andy Hungd1c74342015-07-07 16:54:23 -07001704 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001705 }
1706
1707 sp<AudioTrack> t;
1708 CallbackData *newcbd = NULL;
1709
1710 // We don't attempt to create a new track if we are recycling an
1711 // offloaded track. But, if we are recycling a non-offloaded or we
1712 // are switching where one is offloaded and one isn't then we create
1713 // the new track in advance so that we can read additional stream info
1714
1715 if (!(reuse && bothOffloaded)) {
1716 ALOGV("creating new AudioTrack");
1717
1718 if (mCallback != NULL) {
1719 newcbd = new CallbackData(this);
1720 t = new AudioTrack(
1721 mStreamType,
1722 sampleRate,
1723 format,
1724 channelMask,
1725 frameCount,
1726 flags,
1727 CallbackWrapper,
1728 newcbd,
1729 0, // notification frames
1730 mSessionId,
1731 AudioTrack::TRANSFER_CALLBACK,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001732 offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -08001733 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001734 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001735 mAttributes,
1736 doNotReconnect);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001737 } else {
1738 t = new AudioTrack(
1739 mStreamType,
1740 sampleRate,
1741 format,
1742 channelMask,
1743 frameCount,
1744 flags,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001745 NULL, // callback
1746 NULL, // user data
1747 0, // notification frames
1748 mSessionId,
1749 AudioTrack::TRANSFER_DEFAULT,
1750 NULL, // offload info
Marco Nelissend457c972014-02-11 08:47:07 -08001751 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001752 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001753 mAttributes,
1754 doNotReconnect);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001755 }
1756
1757 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1758 ALOGE("Unable to create audio track");
1759 delete newcbd;
Glenn Kasten3e98ecd2015-05-18 13:13:24 -07001760 // t goes out of scope, so reference count drops to zero
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001761 return NO_INIT;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001762 } else {
1763 // successful AudioTrack initialization implies a legacy stream type was generated
1764 // from the audio attributes
1765 mStreamType = t->streamType();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001766 }
1767 }
1768
1769 if (reuse) {
1770 CHECK(mRecycledTrack != NULL);
1771
1772 if (!bothOffloaded) {
1773 if (mRecycledTrack->frameCount() != t->frameCount()) {
1774 ALOGV("framecount differs: %u/%u frames",
1775 mRecycledTrack->frameCount(), t->frameCount());
1776 reuse = false;
1777 }
1778 }
1779
Marco Nelissen67295b52012-06-11 14:52:53 -07001780 if (reuse) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001781 ALOGV("chaining to next output and recycling track");
Andy Hungd1c74342015-07-07 16:54:23 -07001782 close_l();
Marco Nelissen67295b52012-06-11 14:52:53 -07001783 mTrack = mRecycledTrack;
Glenn Kasten2799d742013-05-30 14:33:29 -07001784 mRecycledTrack.clear();
Marco Nelissen67295b52012-06-11 14:52:53 -07001785 if (mCallbackData != NULL) {
1786 mCallbackData->setOutput(this);
1787 }
Marco Nelissen67295b52012-06-11 14:52:53 -07001788 delete newcbd;
1789 return OK;
1790 }
Marco Nelissen67295b52012-06-11 14:52:53 -07001791 }
1792
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001793 // we're not going to reuse the track, unblock and flush it
1794 // this was done earlier if both tracks are offloaded
1795 if (!bothOffloaded) {
Andy Hungd1c74342015-07-07 16:54:23 -07001796 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001797 }
1798
1799 CHECK((t != NULL) && ((mCallback == NULL) || (newcbd != NULL)));
1800
Marco Nelissen67295b52012-06-11 14:52:53 -07001801 mCallbackData = newcbd;
Steve Block3856b092011-10-20 11:56:00 +01001802 ALOGV("setVolume");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001803 t->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07001804
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001805 mSampleRateHz = sampleRate;
Preetam Singh Ranawat2e17eef2015-08-12 12:11:46 -07001806 mFlags = flags;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001807 mMsecsPerFrame = 1E3f / (mPlaybackRate.mSpeed * sampleRate);
Andy Hungd1c74342015-07-07 16:54:23 -07001808 mFrameSize = t->frameSize();
Marco Nelissen99448602012-04-02 12:16:49 -07001809 uint32_t pos;
1810 if (t->getPosition(&pos) == OK) {
Andy Hungd1c74342015-07-07 16:54:23 -07001811 mBytesWritten = uint64_t(pos) * mFrameSize;
Marco Nelissen99448602012-04-02 12:16:49 -07001812 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001813 mTrack = t;
Eric Laurent2beeb502010-07-16 07:43:46 -07001814
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001815 status_t res = NO_ERROR;
Wei Jia0162d002015-06-09 11:59:33 -07001816 // Note some output devices may give us a direct track even though we don't specify it.
1817 // Example: Line application b/17459982.
Preetam Singh Ranawat2e17eef2015-08-12 12:11:46 -07001818 if ((t->getFlags() & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) {
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001819 res = t->setPlaybackRate(mPlaybackRate);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001820 if (res == NO_ERROR) {
1821 t->setAuxEffectSendLevel(mSendLevel);
1822 res = t->attachAuxEffect(mAuxEffectId);
1823 }
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001824 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001825 ALOGV("open() DONE status %d", res);
1826 return res;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001827}
1828
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001829status_t MediaPlayerService::AudioOutput::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001830{
Steve Block3856b092011-10-20 11:56:00 +01001831 ALOGV("start");
Andy Hungd1c74342015-07-07 16:54:23 -07001832 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001833 if (mCallbackData != NULL) {
1834 mCallbackData->endTrackSwitch();
1835 }
Glenn Kasten2799d742013-05-30 14:33:29 -07001836 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001837 mTrack->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07001838 mTrack->setAuxEffectSendLevel(mSendLevel);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001839 return mTrack->start();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001840 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001841 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001842}
1843
Marco Nelissen6b74d672012-02-28 16:07:44 -08001844void MediaPlayerService::AudioOutput::setNextOutput(const sp<AudioOutput>& nextOutput) {
Andy Hungd1c74342015-07-07 16:54:23 -07001845 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001846 mNextOutput = nextOutput;
1847}
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08001848
Marco Nelissen6b74d672012-02-28 16:07:44 -08001849void MediaPlayerService::AudioOutput::switchToNextOutput() {
1850 ALOGV("switchToNextOutput");
Andy Hungd1c74342015-07-07 16:54:23 -07001851
1852 // Try to acquire the callback lock before moving track (without incurring deadlock).
1853 const unsigned kMaxSwitchTries = 100;
1854 Mutex::Autolock lock(mLock);
1855 for (unsigned tries = 0;;) {
1856 if (mTrack == 0) {
1857 return;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001858 }
Andy Hungd1c74342015-07-07 16:54:23 -07001859 if (mNextOutput != NULL && mNextOutput != this) {
1860 if (mCallbackData != NULL) {
1861 // two alternative approaches
1862#if 1
1863 CallbackData *callbackData = mCallbackData;
1864 mLock.unlock();
1865 // proper acquisition sequence
1866 callbackData->lock();
1867 mLock.lock();
1868 // Caution: it is unlikely that someone deleted our callback or changed our target
1869 if (callbackData != mCallbackData || mNextOutput == NULL || mNextOutput == this) {
1870 // fatal if we are starved out.
1871 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
1872 "switchToNextOutput() cannot obtain correct lock sequence");
1873 callbackData->unlock();
1874 continue;
1875 }
1876 callbackData->mSwitching = true; // begin track switch
1877#else
1878 // tryBeginTrackSwitch() returns false if the callback has the lock.
1879 if (!mCallbackData->tryBeginTrackSwitch()) {
1880 // fatal if we are starved out.
1881 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
1882 "switchToNextOutput() cannot obtain callback lock");
1883 mLock.unlock();
1884 usleep(5 * 1000 /* usec */); // allow callback to use AudioOutput
1885 mLock.lock();
1886 continue;
1887 }
1888#endif
1889 }
1890
1891 Mutex::Autolock nextLock(mNextOutput->mLock);
1892
1893 // If the next output track is not NULL, then it has been
1894 // opened already for playback.
1895 // This is possible even without the next player being started,
1896 // for example, the next player could be prepared and seeked.
1897 //
1898 // Presuming it isn't advisable to force the track over.
1899 if (mNextOutput->mTrack == NULL) {
1900 ALOGD("Recycling track for gapless playback");
1901 delete mNextOutput->mCallbackData;
1902 mNextOutput->mCallbackData = mCallbackData;
1903 mNextOutput->mRecycledTrack = mTrack;
1904 mNextOutput->mSampleRateHz = mSampleRateHz;
1905 mNextOutput->mMsecsPerFrame = mMsecsPerFrame;
1906 mNextOutput->mBytesWritten = mBytesWritten;
1907 mNextOutput->mFlags = mFlags;
1908 mNextOutput->mFrameSize = mFrameSize;
1909 close_l();
1910 mCallbackData = NULL; // destruction handled by mNextOutput
1911 } else {
1912 ALOGW("Ignoring gapless playback because next player has already started");
1913 // remove track in case resource needed for future players.
1914 if (mCallbackData != NULL) {
1915 mCallbackData->endTrackSwitch(); // release lock for callbacks before close.
1916 }
1917 close_l();
1918 }
1919 }
1920 break;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001921 }
1922}
1923
Wei Jia7d3f4df2015-03-03 15:28:00 -08001924ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001925{
Andy Hungd1c74342015-07-07 16:54:23 -07001926 Mutex::Autolock lock(mLock);
Glenn Kastenadad3d72014-02-21 14:51:43 -08001927 LOG_ALWAYS_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
Andreas Huber20111aa2009-07-14 16:56:47 -07001928
Steve Block3856b092011-10-20 11:56:00 +01001929 //ALOGV("write(%p, %u)", buffer, size);
Glenn Kasten2799d742013-05-30 14:33:29 -07001930 if (mTrack != 0) {
Wei Jia7d3f4df2015-03-03 15:28:00 -08001931 ssize_t ret = mTrack->write(buffer, size, blocking);
Andy Hunga31335a2014-08-20 17:37:59 -07001932 if (ret >= 0) {
1933 mBytesWritten += ret;
1934 }
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001935 return ret;
1936 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001937 return NO_INIT;
1938}
1939
1940void MediaPlayerService::AudioOutput::stop()
1941{
Steve Block3856b092011-10-20 11:56:00 +01001942 ALOGV("stop");
Andy Hungd1c74342015-07-07 16:54:23 -07001943 Mutex::Autolock lock(mLock);
Andy Hungda17c042015-06-01 15:53:14 -07001944 mBytesWritten = 0;
Glenn Kasten2799d742013-05-30 14:33:29 -07001945 if (mTrack != 0) mTrack->stop();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001946}
1947
1948void MediaPlayerService::AudioOutput::flush()
1949{
Steve Block3856b092011-10-20 11:56:00 +01001950 ALOGV("flush");
Andy Hungd1c74342015-07-07 16:54:23 -07001951 Mutex::Autolock lock(mLock);
Andy Hungda17c042015-06-01 15:53:14 -07001952 mBytesWritten = 0;
Glenn Kasten2799d742013-05-30 14:33:29 -07001953 if (mTrack != 0) mTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001954}
1955
1956void MediaPlayerService::AudioOutput::pause()
1957{
Steve Block3856b092011-10-20 11:56:00 +01001958 ALOGV("pause");
Andy Hungd1c74342015-07-07 16:54:23 -07001959 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07001960 if (mTrack != 0) mTrack->pause();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001961}
1962
1963void MediaPlayerService::AudioOutput::close()
1964{
Steve Block3856b092011-10-20 11:56:00 +01001965 ALOGV("close");
Erik Wolsheimer7845a1f2015-10-30 12:07:52 -07001966 sp<AudioTrack> track;
1967 {
1968 Mutex::Autolock lock(mLock);
1969 track = mTrack;
1970 close_l(); // clears mTrack
1971 }
1972 // destruction of the track occurs outside of mutex.
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001973}
1974
1975void MediaPlayerService::AudioOutput::setVolume(float left, float right)
1976{
Steve Block3856b092011-10-20 11:56:00 +01001977 ALOGV("setVolume(%f, %f)", left, right);
Andy Hungd1c74342015-07-07 16:54:23 -07001978 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001979 mLeftVolume = left;
1980 mRightVolume = right;
Glenn Kasten2799d742013-05-30 14:33:29 -07001981 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001982 mTrack->setVolume(left, right);
1983 }
1984}
1985
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001986status_t MediaPlayerService::AudioOutput::setPlaybackRate(const AudioPlaybackRate &rate)
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001987{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001988 ALOGV("setPlaybackRate(%f %f %d %d)",
1989 rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Andy Hungd1c74342015-07-07 16:54:23 -07001990 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001991 if (mTrack == 0) {
1992 // remember rate so that we can set it when the track is opened
1993 mPlaybackRate = rate;
1994 return OK;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001995 }
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001996 status_t res = mTrack->setPlaybackRate(rate);
1997 if (res != NO_ERROR) {
1998 return res;
1999 }
2000 // rate.mSpeed is always greater than 0 if setPlaybackRate succeeded
2001 CHECK_GT(rate.mSpeed, 0.f);
2002 mPlaybackRate = rate;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002003 if (mSampleRateHz != 0) {
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002004 mMsecsPerFrame = 1E3f / (rate.mSpeed * mSampleRateHz);
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002005 }
2006 return res;
2007}
2008
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002009status_t MediaPlayerService::AudioOutput::getPlaybackRate(AudioPlaybackRate *rate)
2010{
2011 ALOGV("setPlaybackRate");
Andy Hungd1c74342015-07-07 16:54:23 -07002012 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002013 if (mTrack == 0) {
2014 return NO_INIT;
2015 }
2016 *rate = mTrack->getPlaybackRate();
2017 return NO_ERROR;
2018}
2019
Eric Laurent2beeb502010-07-16 07:43:46 -07002020status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
2021{
Steve Block3856b092011-10-20 11:56:00 +01002022 ALOGV("setAuxEffectSendLevel(%f)", level);
Andy Hungd1c74342015-07-07 16:54:23 -07002023 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002024 mSendLevel = level;
Glenn Kasten2799d742013-05-30 14:33:29 -07002025 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002026 return mTrack->setAuxEffectSendLevel(level);
2027 }
2028 return NO_ERROR;
2029}
2030
2031status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
2032{
Steve Block3856b092011-10-20 11:56:00 +01002033 ALOGV("attachAuxEffect(%d)", effectId);
Andy Hungd1c74342015-07-07 16:54:23 -07002034 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002035 mAuxEffectId = effectId;
Glenn Kasten2799d742013-05-30 14:33:29 -07002036 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002037 return mTrack->attachAuxEffect(effectId);
2038 }
2039 return NO_ERROR;
2040}
2041
Andreas Huber20111aa2009-07-14 16:56:47 -07002042// static
2043void MediaPlayerService::AudioOutput::CallbackWrapper(
Glenn Kastend217a8c2011-06-01 15:20:35 -07002044 int event, void *cookie, void *info) {
Steve Block3856b092011-10-20 11:56:00 +01002045 //ALOGV("callbackwrapper");
Marco Nelissen6b74d672012-02-28 16:07:44 -08002046 CallbackData *data = (CallbackData*)cookie;
Andy Hungd1c74342015-07-07 16:54:23 -07002047 // lock to ensure we aren't caught in the middle of a track switch.
Marco Nelissen6b74d672012-02-28 16:07:44 -08002048 data->lock();
2049 AudioOutput *me = data->getOutput();
Andreas Huber20111aa2009-07-14 16:56:47 -07002050 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002051 if (me == NULL) {
2052 // no output set, likely because the track was scheduled to be reused
2053 // by another player, but the format turned out to be incompatible.
2054 data->unlock();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002055 if (buffer != NULL) {
2056 buffer->size = 0;
2057 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08002058 return;
2059 }
Andreas Huber20111aa2009-07-14 16:56:47 -07002060
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002061 switch(event) {
2062 case AudioTrack::EVENT_MORE_DATA: {
2063 size_t actualSize = (*me->mCallback)(
2064 me, buffer->raw, buffer->size, me->mCallbackCookie,
2065 CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002066
Andy Hung719b46b2015-05-31 22:18:25 -07002067 // Log when no data is returned from the callback.
2068 // (1) We may have no data (especially with network streaming sources).
2069 // (2) We may have reached the EOS and the audio track is not stopped yet.
2070 // Note that AwesomePlayer/AudioPlayer will only return zero size when it reaches the EOS.
2071 // NuPlayerRenderer will return zero when it doesn't have data (it doesn't block to fill).
2072 //
2073 // This is a benign busy-wait, with the next data request generated 10 ms or more later;
2074 // nevertheless for power reasons, we don't want to see too many of these.
Andreas Huber2e8ffaf2010-02-18 16:45:13 -08002075
Andy Hung719b46b2015-05-31 22:18:25 -07002076 ALOGV_IF(actualSize == 0 && buffer->size > 0, "callbackwrapper: empty buffer returned");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002077
Andy Hung719b46b2015-05-31 22:18:25 -07002078 me->mBytesWritten += actualSize; // benign race with reader.
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002079 buffer->size = actualSize;
2080 } break;
2081
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002082 case AudioTrack::EVENT_STREAM_END:
Andy Hung719b46b2015-05-31 22:18:25 -07002083 // currently only occurs for offloaded callbacks
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002084 ALOGV("callbackwrapper: deliver EVENT_STREAM_END");
2085 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2086 me->mCallbackCookie, CB_EVENT_STREAM_END);
2087 break;
2088
2089 case AudioTrack::EVENT_NEW_IAUDIOTRACK :
2090 ALOGV("callbackwrapper: deliver EVENT_TEAR_DOWN");
2091 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2092 me->mCallbackCookie, CB_EVENT_TEAR_DOWN);
2093 break;
2094
Glenn Kasten421743b2015-06-01 08:18:08 -07002095 case AudioTrack::EVENT_UNDERRUN:
Andy Hung719b46b2015-05-31 22:18:25 -07002096 // This occurs when there is no data available, typically
Glenn Kasten421743b2015-06-01 08:18:08 -07002097 // when there is a failure to supply data to the AudioTrack. It can also
2098 // occur in non-offloaded mode when the audio device comes out of standby.
2099 //
Andy Hung719b46b2015-05-31 22:18:25 -07002100 // If an AudioTrack underruns it outputs silence. Since this happens suddenly
2101 // it may sound like an audible pop or glitch.
2102 //
2103 // The underrun event is sent once per track underrun; the condition is reset
2104 // when more data is sent to the AudioTrack.
Glenn Kasten421743b2015-06-01 08:18:08 -07002105 ALOGI("callbackwrapper: EVENT_UNDERRUN (discarded)");
2106 break;
2107
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002108 default:
2109 ALOGE("received unknown event type: %d inside CallbackWrapper !", event);
Andreas Huber51c1e0e2011-04-04 11:43:40 -07002110 }
2111
Marco Nelissen6b74d672012-02-28 16:07:44 -08002112 data->unlock();
Andreas Huber20111aa2009-07-14 16:56:47 -07002113}
2114
Marco Nelissen4110c102012-03-29 09:31:28 -07002115int MediaPlayerService::AudioOutput::getSessionId() const
Eric Laurent8c563ed2010-10-07 18:23:03 -07002116{
Andy Hungd1c74342015-07-07 16:54:23 -07002117 Mutex::Autolock lock(mLock);
Eric Laurent8c563ed2010-10-07 18:23:03 -07002118 return mSessionId;
2119}
2120
Eric Laurent6f59db12013-07-26 17:16:50 -07002121uint32_t MediaPlayerService::AudioOutput::getSampleRate() const
2122{
Andy Hungd1c74342015-07-07 16:54:23 -07002123 Mutex::Autolock lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -07002124 if (mTrack == 0) return 0;
2125 return mTrack->getSampleRate();
2126}
2127
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002128////////////////////////////////////////////////////////////////////////////////
2129
2130struct CallbackThread : public Thread {
2131 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
2132 MediaPlayerBase::AudioSink::AudioCallback cb,
2133 void *cookie);
2134
2135protected:
2136 virtual ~CallbackThread();
2137
2138 virtual bool threadLoop();
2139
2140private:
2141 wp<MediaPlayerBase::AudioSink> mSink;
2142 MediaPlayerBase::AudioSink::AudioCallback mCallback;
2143 void *mCookie;
2144 void *mBuffer;
2145 size_t mBufferSize;
2146
2147 CallbackThread(const CallbackThread &);
2148 CallbackThread &operator=(const CallbackThread &);
2149};
2150
2151CallbackThread::CallbackThread(
2152 const wp<MediaPlayerBase::AudioSink> &sink,
2153 MediaPlayerBase::AudioSink::AudioCallback cb,
2154 void *cookie)
2155 : mSink(sink),
2156 mCallback(cb),
2157 mCookie(cookie),
2158 mBuffer(NULL),
2159 mBufferSize(0) {
2160}
2161
2162CallbackThread::~CallbackThread() {
2163 if (mBuffer) {
2164 free(mBuffer);
2165 mBuffer = NULL;
2166 }
2167}
2168
2169bool CallbackThread::threadLoop() {
2170 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
2171 if (sink == NULL) {
2172 return false;
2173 }
2174
2175 if (mBuffer == NULL) {
2176 mBufferSize = sink->bufferSize();
2177 mBuffer = malloc(mBufferSize);
2178 }
2179
2180 size_t actualSize =
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002181 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie,
2182 MediaPlayerBase::AudioSink::CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002183
2184 if (actualSize > 0) {
2185 sink->write(mBuffer, actualSize);
Andy Hunga31335a2014-08-20 17:37:59 -07002186 // Could return false on sink->write() error or short count.
2187 // Not necessarily appropriate but would work for AudioCache behavior.
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002188 }
2189
2190 return true;
2191}
2192
2193////////////////////////////////////////////////////////////////////////////////
2194
Gloria Wang7cf180c2011-02-19 18:37:57 -08002195void MediaPlayerService::addBatteryData(uint32_t params)
2196{
2197 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002198
2199 int32_t time = systemTime() / 1000000L;
2200
2201 // change audio output devices. This notification comes from AudioFlinger
2202 if ((params & kBatteryDataSpeakerOn)
2203 || (params & kBatteryDataOtherAudioDeviceOn)) {
2204
2205 int deviceOn[NUM_AUDIO_DEVICES];
2206 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2207 deviceOn[i] = 0;
2208 }
2209
2210 if ((params & kBatteryDataSpeakerOn)
2211 && (params & kBatteryDataOtherAudioDeviceOn)) {
2212 deviceOn[SPEAKER_AND_OTHER] = 1;
2213 } else if (params & kBatteryDataSpeakerOn) {
2214 deviceOn[SPEAKER] = 1;
2215 } else {
2216 deviceOn[OTHER_AUDIO_DEVICE] = 1;
2217 }
2218
2219 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2220 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
2221
2222 if (mBatteryAudio.refCount > 0) { // if playing audio
2223 if (!deviceOn[i]) {
2224 mBatteryAudio.lastTime[i] += time;
2225 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2226 mBatteryAudio.lastTime[i] = 0;
2227 } else {
2228 mBatteryAudio.lastTime[i] = 0 - time;
2229 }
2230 }
2231
2232 mBatteryAudio.deviceOn[i] = deviceOn[i];
2233 }
2234 }
2235 return;
2236 }
2237
Marco Nelissenb7848f12014-12-04 08:57:56 -08002238 // an audio stream is started
Gloria Wang9ee159b2011-02-24 14:51:45 -08002239 if (params & kBatteryDataAudioFlingerStart) {
2240 // record the start time only if currently no other audio
2241 // is being played
2242 if (mBatteryAudio.refCount == 0) {
2243 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2244 if (mBatteryAudio.deviceOn[i]) {
2245 mBatteryAudio.lastTime[i] -= time;
2246 }
2247 }
2248 }
2249
2250 mBatteryAudio.refCount ++;
2251 return;
2252
2253 } else if (params & kBatteryDataAudioFlingerStop) {
2254 if (mBatteryAudio.refCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002255 ALOGW("Battery track warning: refCount is <= 0");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002256 return;
2257 }
2258
2259 // record the stop time only if currently this is the only
2260 // audio being played
2261 if (mBatteryAudio.refCount == 1) {
2262 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2263 if (mBatteryAudio.deviceOn[i]) {
2264 mBatteryAudio.lastTime[i] += time;
2265 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2266 mBatteryAudio.lastTime[i] = 0;
2267 }
2268 }
2269 }
2270
2271 mBatteryAudio.refCount --;
2272 return;
2273 }
2274
Gloria Wang7cf180c2011-02-19 18:37:57 -08002275 int uid = IPCThreadState::self()->getCallingUid();
2276 if (uid == AID_MEDIA) {
2277 return;
2278 }
2279 int index = mBatteryData.indexOfKey(uid);
Gloria Wang7cf180c2011-02-19 18:37:57 -08002280
2281 if (index < 0) { // create a new entry for this UID
2282 BatteryUsageInfo info;
2283 info.audioTotalTime = 0;
2284 info.videoTotalTime = 0;
2285 info.audioLastTime = 0;
2286 info.videoLastTime = 0;
2287 info.refCount = 0;
2288
Gloria Wang9ee159b2011-02-24 14:51:45 -08002289 if (mBatteryData.add(uid, info) == NO_MEMORY) {
Steve Block29357bc2012-01-06 19:20:56 +00002290 ALOGE("Battery track error: no memory for new app");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002291 return;
2292 }
Gloria Wang7cf180c2011-02-19 18:37:57 -08002293 }
2294
2295 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
2296
2297 if (params & kBatteryDataCodecStarted) {
2298 if (params & kBatteryDataTrackAudio) {
2299 info.audioLastTime -= time;
2300 info.refCount ++;
2301 }
2302 if (params & kBatteryDataTrackVideo) {
2303 info.videoLastTime -= time;
2304 info.refCount ++;
2305 }
2306 } else {
2307 if (info.refCount == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002308 ALOGW("Battery track warning: refCount is already 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002309 return;
2310 } else if (info.refCount < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00002311 ALOGE("Battery track error: refCount < 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002312 mBatteryData.removeItem(uid);
2313 return;
2314 }
2315
2316 if (params & kBatteryDataTrackAudio) {
2317 info.audioLastTime += time;
2318 info.refCount --;
2319 }
2320 if (params & kBatteryDataTrackVideo) {
2321 info.videoLastTime += time;
2322 info.refCount --;
2323 }
2324
2325 // no stream is being played by this UID
2326 if (info.refCount == 0) {
2327 info.audioTotalTime += info.audioLastTime;
2328 info.audioLastTime = 0;
2329 info.videoTotalTime += info.videoLastTime;
2330 info.videoLastTime = 0;
2331 }
2332 }
2333}
2334
2335status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
2336 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002337
2338 // audio output devices usage
2339 int32_t time = systemTime() / 1000000L; //in ms
2340 int32_t totalTime;
2341
2342 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2343 totalTime = mBatteryAudio.totalTime[i];
2344
2345 if (mBatteryAudio.deviceOn[i]
2346 && (mBatteryAudio.lastTime[i] != 0)) {
2347 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
2348 totalTime += tmpTime;
2349 }
2350
2351 reply->writeInt32(totalTime);
2352 // reset the total time
2353 mBatteryAudio.totalTime[i] = 0;
2354 }
2355
2356 // codec usage
Gloria Wang7cf180c2011-02-19 18:37:57 -08002357 BatteryUsageInfo info;
2358 int size = mBatteryData.size();
2359
2360 reply->writeInt32(size);
2361 int i = 0;
2362
2363 while (i < size) {
2364 info = mBatteryData.valueAt(i);
2365
2366 reply->writeInt32(mBatteryData.keyAt(i)); //UID
2367 reply->writeInt32(info.audioTotalTime);
2368 reply->writeInt32(info.videoTotalTime);
2369
2370 info.audioTotalTime = 0;
2371 info.videoTotalTime = 0;
2372
2373 // remove the UID entry where no stream is being played
2374 if (info.refCount <= 0) {
2375 mBatteryData.removeItemsAt(i);
2376 size --;
2377 i --;
2378 }
2379 i++;
2380 }
2381 return NO_ERROR;
2382}
nikoa64c8c72009-07-20 15:07:26 -07002383} // namespace android