blob: 9b081e997e630fda0667414e6cf04e97e83400e7 [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>
Marco Nelissen83b0fd92015-09-16 13:48:07 -070060#include <media/stagefright/Utils.h>
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +010061#include <media/stagefright/foundation/ADebug.h>
Marco Nelissenf09611f2015-02-13 14:12:42 -080062#include <media/stagefright/foundation/ALooperRoster.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070063#include <mediautils/BatteryNotifier.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080064
Andy Hung53541292016-04-13 16:48:51 -070065#include <memunreachable/memunreachable.h>
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 Huberf9334412010-12-15 15:17:42 -080077#include "nuplayer/NuPlayerDriver.h"
Andreas Huber20111aa2009-07-14 16:56:47 -070078
Andreas Huber20111aa2009-07-14 16:56:47 -070079#include <OMX.h>
Nicolas Catania14d27472009-07-13 14:37:49 -070080
Andreas Hubered3e3e02012-03-26 11:13:27 -070081#include "Crypto.h"
Jeff Tinkercc82dc62013-02-08 10:18:35 -080082#include "Drm.h"
Andreas Huber59451f82012-09-18 10:36:32 -070083#include "HDCP.h"
Andreas Huberb7319a72013-05-29 14:20:52 -070084#include "HTTPBase.h"
Andreas Huber35213f12012-08-29 11:41:50 -070085#include "RemoteDisplay.h"
Andreas Hubered3e3e02012-03-26 11:13:27 -070086
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070087namespace {
nikoa64c8c72009-07-20 15:07:26 -070088using android::media::Metadata;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070089using android::status_t;
90using android::OK;
91using android::BAD_VALUE;
92using android::NOT_ENOUGH_DATA;
93using android::Parcel;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070094
95// Max number of entries in the filter.
96const int kMaxFilterSize = 64; // I pulled that out of thin air.
97
Andy Hungff874dc2016-04-11 16:49:09 -070098const float kMaxRequiredSpeed = 8.0f; // for PCM tracks allow up to 8x speedup.
99
nikoa64c8c72009-07-20 15:07:26 -0700100// FIXME: Move all the metadata related function in the Metadata.cpp
nikod608a812009-07-16 16:39:53 -0700101
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700102
103// Unmarshall a filter from a Parcel.
104// Filter format in a parcel:
105//
106// 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
107// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
108// | number of entries (n) |
109// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
110// | metadata type 1 |
111// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
112// | metadata type 2 |
113// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
114// ....
115// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
116// | metadata type n |
117// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
118//
119// @param p Parcel that should start with a filter.
120// @param[out] filter On exit contains the list of metadata type to be
121// filtered.
122// @param[out] status On exit contains the status code to be returned.
123// @return true if the parcel starts with a valid filter.
124bool unmarshallFilter(const Parcel& p,
nikoa64c8c72009-07-20 15:07:26 -0700125 Metadata::Filter *filter,
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700126 status_t *status)
127{
Nicolas Catania48290382009-07-10 13:53:06 -0700128 int32_t val;
129 if (p.readInt32(&val) != OK)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700130 {
Steve Block29357bc2012-01-06 19:20:56 +0000131 ALOGE("Failed to read filter's length");
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700132 *status = NOT_ENOUGH_DATA;
133 return false;
134 }
135
Nicolas Catania48290382009-07-10 13:53:06 -0700136 if( val > kMaxFilterSize || val < 0)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700137 {
Steve Block29357bc2012-01-06 19:20:56 +0000138 ALOGE("Invalid filter len %d", val);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700139 *status = BAD_VALUE;
140 return false;
141 }
142
Nicolas Catania48290382009-07-10 13:53:06 -0700143 const size_t num = val;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700144
145 filter->clear();
Nicolas Catania48290382009-07-10 13:53:06 -0700146 filter->setCapacity(num);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700147
nikoa64c8c72009-07-20 15:07:26 -0700148 size_t size = num * sizeof(Metadata::Type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700149
Nicolas Catania48290382009-07-10 13:53:06 -0700150
151 if (p.dataAvail() < size)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700152 {
Andy Hung833b4752016-04-04 17:15:48 -0700153 ALOGE("Filter too short expected %zu but got %zu", size, p.dataAvail());
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700154 *status = NOT_ENOUGH_DATA;
155 return false;
156 }
157
nikoa64c8c72009-07-20 15:07:26 -0700158 const Metadata::Type *data =
159 static_cast<const Metadata::Type*>(p.readInplace(size));
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700160
Nicolas Catania48290382009-07-10 13:53:06 -0700161 if (NULL == data)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700162 {
Steve Block29357bc2012-01-06 19:20:56 +0000163 ALOGE("Filter had no data");
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700164 *status = BAD_VALUE;
165 return false;
166 }
167
168 // TODO: The stl impl of vector would be more efficient here
169 // because it degenerates into a memcpy on pod types. Try to
170 // replace later or use stl::set.
Nicolas Catania48290382009-07-10 13:53:06 -0700171 for (size_t i = 0; i < num; ++i)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700172 {
Nicolas Catania48290382009-07-10 13:53:06 -0700173 filter->add(*data);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700174 ++data;
175 }
176 *status = OK;
177 return true;
178}
179
Nicolas Catania48290382009-07-10 13:53:06 -0700180// @param filter Of metadata type.
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700181// @param val To be searched.
182// @return true if a match was found.
nikoa64c8c72009-07-20 15:07:26 -0700183bool findMetadata(const Metadata::Filter& filter, const int32_t val)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700184{
185 // Deal with empty and ANY right away
186 if (filter.isEmpty()) return false;
nikoa64c8c72009-07-20 15:07:26 -0700187 if (filter[0] == Metadata::kAny) return true;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700188
Nicolas Catania48290382009-07-10 13:53:06 -0700189 return filter.indexOf(val) >= 0;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700190}
191
192} // anonymous namespace
193
194
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700195namespace {
196using android::Parcel;
197using android::String16;
198
199// marshalling tag indicating flattened utf16 tags
200// keep in sync with frameworks/base/media/java/android/media/AudioAttributes.java
201const int32_t kAudioAttributesMarshallTagFlattenTags = 1;
202
203// Audio attributes format in a parcel:
204//
205// 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
206// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
207// | usage |
208// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
209// | content_type |
210// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Hyejin Kim4f418f92014-09-05 15:50:03 +0900211// | source |
212// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700213// | flags |
214// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
215// | kAudioAttributesMarshallTagFlattenTags | // ignore tags if not found
216// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
217// | flattened tags in UTF16 |
218// | ... |
219// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
220//
221// @param p Parcel that contains audio attributes.
222// @param[out] attributes On exit points to an initialized audio_attributes_t structure
223// @param[out] status On exit contains the status code to be returned.
224void unmarshallAudioAttributes(const Parcel& parcel, audio_attributes_t *attributes)
225{
226 attributes->usage = (audio_usage_t) parcel.readInt32();
227 attributes->content_type = (audio_content_type_t) parcel.readInt32();
Hyejin Kim4f418f92014-09-05 15:50:03 +0900228 attributes->source = (audio_source_t) parcel.readInt32();
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700229 attributes->flags = (audio_flags_mask_t) parcel.readInt32();
230 const bool hasFlattenedTag = (parcel.readInt32() == kAudioAttributesMarshallTagFlattenTags);
231 if (hasFlattenedTag) {
232 // the tags are UTF16, convert to UTF8
233 String16 tags = parcel.readString16();
234 ssize_t realTagSize = utf16_to_utf8_length(tags.string(), tags.size());
235 if (realTagSize <= 0) {
236 strcpy(attributes->tags, "");
237 } else {
238 // copy the flattened string into the attributes as the destination for the conversion:
239 // copying array size -1, array for tags was calloc'd, no need to NULL-terminate it
240 size_t tagSize = realTagSize > AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 ?
241 AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 : realTagSize;
242 utf16_to_utf8(tags.string(), tagSize, attributes->tags);
243 }
244 } else {
245 ALOGE("unmarshallAudioAttributes() received unflattened tags, ignoring tag values");
246 strcpy(attributes->tags, "");
247 }
248}
249} // anonymous namespace
250
251
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800252namespace android {
253
Marco Nelissenf09611f2015-02-13 14:12:42 -0800254extern ALooperRoster gLooperRoster;
255
256
Dave Burked681bbb2011-08-30 14:39:17 +0100257static bool checkPermission(const char* permissionString) {
Dave Burked681bbb2011-08-30 14:39:17 +0100258 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
259 bool ok = checkCallingPermission(String16(permissionString));
Steve Block29357bc2012-01-06 19:20:56 +0000260 if (!ok) ALOGE("Request requires %s", permissionString);
Dave Burked681bbb2011-08-30 14:39:17 +0100261 return ok;
262}
263
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800264// 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 -0800265/* static */ int MediaPlayerService::AudioOutput::mMinBufferCount = 4;
266/* static */ bool MediaPlayerService::AudioOutput::mIsOnEmulator = false;
267
268void MediaPlayerService::instantiate() {
269 defaultServiceManager()->addService(
270 String16("media.player"), new MediaPlayerService());
271}
272
273MediaPlayerService::MediaPlayerService()
274{
Steve Block3856b092011-10-20 11:56:00 +0100275 ALOGV("MediaPlayerService created");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800276 mNextConnId = 1;
Gloria Wang9ee159b2011-02-24 14:51:45 -0800277
278 mBatteryAudio.refCount = 0;
279 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
280 mBatteryAudio.deviceOn[i] = 0;
281 mBatteryAudio.lastTime[i] = 0;
282 mBatteryAudio.totalTime[i] = 0;
283 }
284 // speaker is on by default
285 mBatteryAudio.deviceOn[SPEAKER] = 1;
John Grossman44a7e422012-06-21 17:29:24 -0700286
Chong Zhang0b30fd42014-07-23 14:46:05 -0700287 // reset battery stats
288 // if the mediaserver has crashed, battery stats could be left
289 // in bad state, reset the state upon service start.
Wei Jia3f273d12015-11-24 09:06:49 -0800290 BatteryNotifier::getInstance().noteResetVideo();
Chong Zhang0b30fd42014-07-23 14:46:05 -0700291
John Grossman44a7e422012-06-21 17:29:24 -0700292 MediaPlayerFactory::registerBuiltinFactories();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800293}
294
295MediaPlayerService::~MediaPlayerService()
296{
Steve Block3856b092011-10-20 11:56:00 +0100297 ALOGV("MediaPlayerService destroyed");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800298}
299
Svet Ganovbe71aa22015-04-28 12:06:02 -0700300sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(const String16 &opPackageName)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800301{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800302 pid_t pid = IPCThreadState::self()->getCallingPid();
Svet Ganovbe71aa22015-04-28 12:06:02 -0700303 sp<MediaRecorderClient> recorder = new MediaRecorderClient(this, pid, opPackageName);
Gloria Wangdac6a312009-10-29 15:46:37 -0700304 wp<MediaRecorderClient> w = recorder;
305 Mutex::Autolock lock(mLock);
306 mMediaRecorderClients.add(w);
Steve Block3856b092011-10-20 11:56:00 +0100307 ALOGV("Create new media recorder client from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800308 return recorder;
309}
310
Gloria Wangdac6a312009-10-29 15:46:37 -0700311void MediaPlayerService::removeMediaRecorderClient(wp<MediaRecorderClient> client)
312{
313 Mutex::Autolock lock(mLock);
314 mMediaRecorderClients.remove(client);
Steve Block3856b092011-10-20 11:56:00 +0100315 ALOGV("Delete media recorder client");
Gloria Wangdac6a312009-10-29 15:46:37 -0700316}
317
Glenn Kastenf37971f2012-02-03 11:06:53 -0800318sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800319{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800320 pid_t pid = IPCThreadState::self()->getCallingPid();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800321 sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
Steve Block3856b092011-10-20 11:56:00 +0100322 ALOGV("Create new media retriever from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800323 return retriever;
324}
325
Glenn Kastenf37971f2012-02-03 11:06:53 -0800326sp<IMediaPlayer> MediaPlayerService::create(const sp<IMediaPlayerClient>& client,
Glenn Kastend848eb42016-03-08 13:42:11 -0800327 audio_session_t audioSessionId)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800328{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800329 pid_t pid = IPCThreadState::self()->getCallingPid();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800330 int32_t connId = android_atomic_inc(&mNextConnId);
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700331
332 sp<Client> c = new Client(
333 this, pid, connId, client, audioSessionId,
334 IPCThreadState::self()->getCallingUid());
335
Steve Block3856b092011-10-20 11:56:00 +0100336 ALOGV("Create new client(%d) from pid %d, uid %d, ", connId, pid,
Dave Burked681bbb2011-08-30 14:39:17 +0100337 IPCThreadState::self()->getCallingUid());
338
339 wp<Client> w = c;
340 {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800341 Mutex::Autolock lock(mLock);
342 mClients.add(w);
343 }
Andreas Hubere2b10282010-11-23 11:41:34 -0800344 return c;
345}
346
Lajos Molnar1381d4b2014-08-07 15:18:35 -0700347sp<IMediaCodecList> MediaPlayerService::getCodecList() const {
348 return MediaCodecList::getLocalInstance();
349}
350
Marco Nelissen260e56c2016-01-28 21:41:25 +0000351sp<IOMX> MediaPlayerService::getOMX() {
Marco Nelissen1900e772016-02-02 16:12:16 -0800352 ALOGI("MediaPlayerService::getOMX");
Marco Nelissen260e56c2016-01-28 21:41:25 +0000353 Mutex::Autolock autoLock(mLock);
354
355 if (mOMX.get() == NULL) {
356 mOMX = new OMX;
357 }
358
359 return mOMX;
360}
361
Andreas Hubered3e3e02012-03-26 11:13:27 -0700362sp<ICrypto> MediaPlayerService::makeCrypto() {
Andreas Huber1bd139a2012-04-03 14:19:20 -0700363 return new Crypto;
Andreas Hubered3e3e02012-03-26 11:13:27 -0700364}
365
Jeff Tinkercc82dc62013-02-08 10:18:35 -0800366sp<IDrm> MediaPlayerService::makeDrm() {
367 return new Drm;
368}
369
Andreas Huber279dcd82013-01-30 10:41:25 -0800370sp<IHDCP> MediaPlayerService::makeHDCP(bool createEncryptionModule) {
371 return new HDCP(createEncryptionModule);
Andreas Huber59451f82012-09-18 10:36:32 -0700372}
373
Jeff Brown2013a542012-09-04 21:38:42 -0700374sp<IRemoteDisplay> MediaPlayerService::listenForRemoteDisplay(
Svet Ganovbe71aa22015-04-28 12:06:02 -0700375 const String16 &opPackageName,
Jeff Brown2013a542012-09-04 21:38:42 -0700376 const sp<IRemoteDisplayClient>& client, const String8& iface) {
Jeff Brownaba33d52012-09-07 17:38:58 -0700377 if (!checkPermission("android.permission.CONTROL_WIFI_DISPLAY")) {
378 return NULL;
379 }
380
Svet Ganovbe71aa22015-04-28 12:06:02 -0700381 return new RemoteDisplay(opPackageName, client, iface.string());
Jeff Brown2013a542012-09-04 21:38:42 -0700382}
383
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800384status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
385{
386 const size_t SIZE = 256;
387 char buffer[SIZE];
388 String8 result;
389
390 result.append(" AudioOutput\n");
391 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n",
392 mStreamType, mLeftVolume, mRightVolume);
393 result.append(buffer);
394 snprintf(buffer, 255, " msec per frame(%f), latency (%d)\n",
Eric Laurentdb354e52012-03-05 17:27:11 -0800395 mMsecsPerFrame, (mTrack != 0) ? mTrack->latency() : -1);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800396 result.append(buffer);
Eric Laurent2beeb502010-07-16 07:43:46 -0700397 snprintf(buffer, 255, " aux effect id(%d), send level (%f)\n",
398 mAuxEffectId, mSendLevel);
399 result.append(buffer);
400
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800401 ::write(fd, result.string(), result.size());
402 if (mTrack != 0) {
403 mTrack->dump(fd, args);
404 }
405 return NO_ERROR;
406}
407
Lajos Molnar6d339f12015-04-17 16:15:53 -0700408status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800409{
410 const size_t SIZE = 256;
411 char buffer[SIZE];
412 String8 result;
413 result.append(" Client\n");
414 snprintf(buffer, 255, " pid(%d), connId(%d), status(%d), looping(%s)\n",
415 mPid, mConnId, mStatus, mLoop?"true": "false");
416 result.append(buffer);
417 write(fd, result.string(), result.size());
Andreas Hubera0b1d4b2011-06-07 15:52:25 -0700418 if (mPlayer != NULL) {
419 mPlayer->dump(fd, args);
420 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800421 if (mAudioOutput != 0) {
422 mAudioOutput->dump(fd, args);
423 }
424 write(fd, "\n", 1);
425 return NO_ERROR;
426}
427
Marco Nelissenf09611f2015-02-13 14:12:42 -0800428/**
429 * The only arguments this understands right now are -c, -von and -voff,
430 * which are parsed by ALooperRoster::dump()
431 */
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800432status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
433{
434 const size_t SIZE = 256;
435 char buffer[SIZE];
436 String8 result;
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530437 SortedVector< sp<Client> > clients; //to serialise the mutex unlock & client destruction.
438 SortedVector< sp<MediaRecorderClient> > mediaRecorderClients;
439
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800440 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
441 snprintf(buffer, SIZE, "Permission Denial: "
442 "can't dump MediaPlayerService from pid=%d, uid=%d\n",
443 IPCThreadState::self()->getCallingPid(),
444 IPCThreadState::self()->getCallingUid());
445 result.append(buffer);
446 } else {
447 Mutex::Autolock lock(mLock);
448 for (int i = 0, n = mClients.size(); i < n; ++i) {
449 sp<Client> c = mClients[i].promote();
450 if (c != 0) c->dump(fd, args);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530451 clients.add(c);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800452 }
James Dongb9141222010-07-08 11:16:11 -0700453 if (mMediaRecorderClients.size() == 0) {
454 result.append(" No media recorder client\n\n");
455 } else {
456 for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
457 sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
James Donge579e282011-10-18 22:29:20 -0700458 if (c != 0) {
459 snprintf(buffer, 255, " MediaRecorderClient pid(%d)\n", c->mPid);
460 result.append(buffer);
461 write(fd, result.string(), result.size());
462 result = "\n";
463 c->dump(fd, args);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530464 mediaRecorderClients.add(c);
James Donge579e282011-10-18 22:29:20 -0700465 }
James Dongb9141222010-07-08 11:16:11 -0700466 }
Gloria Wangdac6a312009-10-29 15:46:37 -0700467 }
468
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800469 result.append(" Files opened and/or mapped:\n");
Marco Nelissenf09611f2015-02-13 14:12:42 -0800470 snprintf(buffer, SIZE, "/proc/%d/maps", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800471 FILE *f = fopen(buffer, "r");
472 if (f) {
473 while (!feof(f)) {
474 fgets(buffer, SIZE, f);
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700475 if (strstr(buffer, " /storage/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800476 strstr(buffer, " /system/sounds/") ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700477 strstr(buffer, " /data/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800478 strstr(buffer, " /system/media/")) {
479 result.append(" ");
480 result.append(buffer);
481 }
482 }
483 fclose(f);
484 } else {
485 result.append("couldn't open ");
486 result.append(buffer);
487 result.append("\n");
488 }
489
Marco Nelissenf09611f2015-02-13 14:12:42 -0800490 snprintf(buffer, SIZE, "/proc/%d/fd", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800491 DIR *d = opendir(buffer);
492 if (d) {
493 struct dirent *ent;
494 while((ent = readdir(d)) != NULL) {
495 if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
Marco Nelissenf09611f2015-02-13 14:12:42 -0800496 snprintf(buffer, SIZE, "/proc/%d/fd/%s", getpid(), ent->d_name);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800497 struct stat s;
498 if (lstat(buffer, &s) == 0) {
499 if ((s.st_mode & S_IFMT) == S_IFLNK) {
500 char linkto[256];
501 int len = readlink(buffer, linkto, sizeof(linkto));
502 if(len > 0) {
503 if(len > 255) {
504 linkto[252] = '.';
505 linkto[253] = '.';
506 linkto[254] = '.';
507 linkto[255] = 0;
508 } else {
509 linkto[len] = 0;
510 }
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700511 if (strstr(linkto, "/storage/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800512 strstr(linkto, "/system/sounds/") == linkto ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700513 strstr(linkto, "/data/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800514 strstr(linkto, "/system/media/") == linkto) {
515 result.append(" ");
516 result.append(buffer);
517 result.append(" -> ");
518 result.append(linkto);
519 result.append("\n");
520 }
521 }
522 } else {
523 result.append(" unexpected type for ");
524 result.append(buffer);
525 result.append("\n");
526 }
527 }
528 }
529 }
530 closedir(d);
531 } else {
532 result.append("couldn't open ");
533 result.append(buffer);
534 result.append("\n");
535 }
536
Marco Nelissenf09611f2015-02-13 14:12:42 -0800537 gLooperRoster.dump(fd, args);
538
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800539 bool dumpMem = false;
Andy Hung53541292016-04-13 16:48:51 -0700540 bool unreachableMemory = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800541 for (size_t i = 0; i < args.size(); i++) {
542 if (args[i] == String16("-m")) {
543 dumpMem = true;
Andy Hung53541292016-04-13 16:48:51 -0700544 } else if (args[i] == String16("--unreachable")) {
545 unreachableMemory = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800546 }
547 }
548 if (dumpMem) {
James Dong8635b7b2011-03-14 17:01:38 -0700549 dumpMemoryAddresses(fd);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800550 }
Andy Hung53541292016-04-13 16:48:51 -0700551 if (unreachableMemory) {
552 result.append("\nDumping unreachable memory:\n");
553 // TODO - should limit be an argument parameter?
554 std::string s = GetUnreachableMemoryString(true /* contents */, 10000 /* limit */);
555 result.append(s.c_str(), s.size());
556 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800557 }
558 write(fd, result.string(), result.size());
559 return NO_ERROR;
560}
561
562void MediaPlayerService::removeClient(wp<Client> client)
563{
564 Mutex::Autolock lock(mLock);
565 mClients.remove(client);
566}
567
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700568MediaPlayerService::Client::Client(
569 const sp<MediaPlayerService>& service, pid_t pid,
570 int32_t connId, const sp<IMediaPlayerClient>& client,
Glenn Kastend848eb42016-03-08 13:42:11 -0800571 audio_session_t audioSessionId, uid_t uid)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800572{
Steve Block3856b092011-10-20 11:56:00 +0100573 ALOGV("Client(%d) constructor", connId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800574 mPid = pid;
575 mConnId = connId;
576 mService = service;
577 mClient = client;
578 mLoop = false;
579 mStatus = NO_INIT;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700580 mAudioSessionId = audioSessionId;
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700581 mUID = uid;
John Grossmanc795b642012-02-22 15:38:35 -0800582 mRetransmitEndpointValid = false;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700583 mAudioAttributes = NULL;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700584
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800585#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000586 ALOGD("create Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800587 mAntagonizer = new Antagonizer(notify, this);
588#endif
589}
590
591MediaPlayerService::Client::~Client()
592{
Steve Block3856b092011-10-20 11:56:00 +0100593 ALOGV("Client(%d) destructor pid = %d", mConnId, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800594 mAudioOutput.clear();
595 wp<Client> client(this);
596 disconnect();
597 mService->removeClient(client);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700598 if (mAudioAttributes != NULL) {
599 free(mAudioAttributes);
600 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800601}
602
603void MediaPlayerService::Client::disconnect()
604{
Steve Block3856b092011-10-20 11:56:00 +0100605 ALOGV("disconnect(%d) from pid %d", mConnId, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800606 // grab local reference and clear main reference to prevent future
607 // access to object
608 sp<MediaPlayerBase> p;
609 {
610 Mutex::Autolock l(mLock);
611 p = mPlayer;
beanzdcfefde2012-11-05 09:51:43 +0800612 mClient.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800613 }
Andreas Huber20111aa2009-07-14 16:56:47 -0700614
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800615 mPlayer.clear();
616
617 // clear the notification to prevent callbacks to dead client
618 // and reset the player. We assume the player will serialize
619 // access to itself if necessary.
620 if (p != 0) {
621 p->setNotifyCallback(0, 0);
622#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000623 ALOGD("kill Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800624 mAntagonizer->kill();
625#endif
626 p->reset();
627 }
628
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700629 disconnectNativeWindow();
630
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800631 IPCThreadState::self()->flushCommands();
632}
633
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800634sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
635{
636 // determine if we have the right player type
637 sp<MediaPlayerBase> p = mPlayer;
638 if ((p != NULL) && (p->playerType() != playerType)) {
Steve Block3856b092011-10-20 11:56:00 +0100639 ALOGV("delete player");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800640 p.clear();
641 }
642 if (p == NULL) {
Ronghua Wu68845c12015-07-21 09:50:48 -0700643 p = MediaPlayerFactory::createPlayer(playerType, this, notify, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800644 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700645
Jason Simmonsdb29e522011-08-12 13:46:55 -0700646 if (p != NULL) {
647 p->setUID(mUID);
648 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700649
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800650 return p;
651}
652
John Grossmanc795b642012-02-22 15:38:35 -0800653sp<MediaPlayerBase> MediaPlayerService::Client::setDataSource_pre(
654 player_type playerType)
655{
656 ALOGV("player type = %d", playerType);
657
658 // create the right type of player
659 sp<MediaPlayerBase> p = createPlayer(playerType);
660 if (p == NULL) {
661 return p;
662 }
663
664 if (!p->hardwareOutput()) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -0700665 Mutex::Autolock l(mLock);
Marco Nelissend457c972014-02-11 08:47:07 -0800666 mAudioOutput = new AudioOutput(mAudioSessionId, IPCThreadState::self()->getCallingUid(),
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700667 mPid, mAudioAttributes);
John Grossmanc795b642012-02-22 15:38:35 -0800668 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
669 }
670
671 return p;
672}
673
674void MediaPlayerService::Client::setDataSource_post(
675 const sp<MediaPlayerBase>& p,
676 status_t status)
677{
678 ALOGV(" setDataSource");
679 mStatus = status;
680 if (mStatus != OK) {
681 ALOGE(" error: %d", mStatus);
682 return;
683 }
684
685 // Set the re-transmission endpoint if one was chosen.
686 if (mRetransmitEndpointValid) {
687 mStatus = p->setRetransmitEndpoint(&mRetransmitEndpoint);
688 if (mStatus != NO_ERROR) {
689 ALOGE("setRetransmitEndpoint error: %d", mStatus);
690 }
691 }
692
693 if (mStatus == OK) {
694 mPlayer = p;
695 }
696}
697
Andreas Huber2db84552010-01-28 11:19:57 -0800698status_t MediaPlayerService::Client::setDataSource(
Andreas Huber1b86fe02014-01-29 11:13:26 -0800699 const sp<IMediaHTTPService> &httpService,
700 const char *url,
701 const KeyedVector<String8, String8> *headers)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800702{
Steve Block3856b092011-10-20 11:56:00 +0100703 ALOGV("setDataSource(%s)", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800704 if (url == NULL)
705 return UNKNOWN_ERROR;
706
Dave Burked681bbb2011-08-30 14:39:17 +0100707 if ((strncmp(url, "http://", 7) == 0) ||
708 (strncmp(url, "https://", 8) == 0) ||
709 (strncmp(url, "rtsp://", 7) == 0)) {
710 if (!checkPermission("android.permission.INTERNET")) {
711 return PERMISSION_DENIED;
712 }
713 }
714
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800715 if (strncmp(url, "content://", 10) == 0) {
716 // get a filedescriptor for the content Uri and
717 // pass it to the setDataSource(fd) method
718
719 String16 url16(url);
720 int fd = android::openContentProviderFile(url16);
721 if (fd < 0)
722 {
Steve Block29357bc2012-01-06 19:20:56 +0000723 ALOGE("Couldn't open fd for %s", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800724 return UNKNOWN_ERROR;
725 }
726 setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
727 close(fd);
728 return mStatus;
729 } else {
John Grossman44a7e422012-06-21 17:29:24 -0700730 player_type playerType = MediaPlayerFactory::getPlayerType(this, url);
John Grossmanc795b642012-02-22 15:38:35 -0800731 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
732 if (p == NULL) {
733 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800734 }
735
Andreas Huber1b86fe02014-01-29 11:13:26 -0800736 setDataSource_post(p, p->setDataSource(httpService, url, headers));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800737 return mStatus;
738 }
739}
740
741status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
742{
Marco Nelissen83b0fd92015-09-16 13:48:07 -0700743 ALOGV("setDataSource fd=%d (%s), offset=%lld, length=%lld",
744 fd, nameForFd(fd).c_str(), (long long) offset, (long long) length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800745 struct stat sb;
746 int ret = fstat(fd, &sb);
747 if (ret != 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000748 ALOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800749 return UNKNOWN_ERROR;
750 }
751
Andy Hung833b4752016-04-04 17:15:48 -0700752 ALOGV("st_dev = %llu", static_cast<unsigned long long>(sb.st_dev));
Steve Block3856b092011-10-20 11:56:00 +0100753 ALOGV("st_mode = %u", sb.st_mode);
Mark Salyzyn77342f72014-06-18 16:31:32 -0700754 ALOGV("st_uid = %lu", static_cast<unsigned long>(sb.st_uid));
755 ALOGV("st_gid = %lu", static_cast<unsigned long>(sb.st_gid));
Andy Hung833b4752016-04-04 17:15:48 -0700756 ALOGV("st_size = %llu", static_cast<unsigned long long>(sb.st_size));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800757
758 if (offset >= sb.st_size) {
Steve Block29357bc2012-01-06 19:20:56 +0000759 ALOGE("offset error");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800760 return UNKNOWN_ERROR;
761 }
762 if (offset + length > sb.st_size) {
763 length = sb.st_size - offset;
Andy Hung833b4752016-04-04 17:15:48 -0700764 ALOGV("calculated length = %lld", (long long)length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800765 }
766
John Grossman44a7e422012-06-21 17:29:24 -0700767 player_type playerType = MediaPlayerFactory::getPlayerType(this,
768 fd,
769 offset,
770 length);
John Grossmanc795b642012-02-22 15:38:35 -0800771 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
772 if (p == NULL) {
773 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800774 }
775
776 // now set data source
John Grossmanc795b642012-02-22 15:38:35 -0800777 setDataSource_post(p, p->setDataSource(fd, offset, length));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800778 return mStatus;
779}
780
Andreas Hubere2b10282010-11-23 11:41:34 -0800781status_t MediaPlayerService::Client::setDataSource(
782 const sp<IStreamSource> &source) {
783 // create the right type of player
John Grossman44a7e422012-06-21 17:29:24 -0700784 player_type playerType = MediaPlayerFactory::getPlayerType(this, source);
John Grossmanc795b642012-02-22 15:38:35 -0800785 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
Andreas Hubere2b10282010-11-23 11:41:34 -0800786 if (p == NULL) {
787 return NO_INIT;
788 }
789
Andreas Hubere2b10282010-11-23 11:41:34 -0800790 // now set data source
John Grossmanc795b642012-02-22 15:38:35 -0800791 setDataSource_post(p, p->setDataSource(source));
Andreas Hubere2b10282010-11-23 11:41:34 -0800792 return mStatus;
793}
794
Chris Watkins99f31602015-03-20 13:06:33 -0700795status_t MediaPlayerService::Client::setDataSource(
796 const sp<IDataSource> &source) {
797 sp<DataSource> dataSource = DataSource::CreateFromIDataSource(source);
798 player_type playerType = MediaPlayerFactory::getPlayerType(this, dataSource);
799 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
800 if (p == NULL) {
801 return NO_INIT;
802 }
803 // now set data source
804 setDataSource_post(p, p->setDataSource(dataSource));
805 return mStatus;
806}
807
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700808void MediaPlayerService::Client::disconnectNativeWindow() {
809 if (mConnectedWindow != NULL) {
810 status_t err = native_window_api_disconnect(mConnectedWindow.get(),
811 NATIVE_WINDOW_API_MEDIA);
812
813 if (err != OK) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000814 ALOGW("native_window_api_disconnect returned an error: %s (%d)",
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700815 strerror(-err), err);
816 }
817 }
818 mConnectedWindow.clear();
819}
820
Glenn Kasten11731182011-02-08 17:26:17 -0800821status_t MediaPlayerService::Client::setVideoSurfaceTexture(
Andy McFadden484566c2012-12-18 09:46:54 -0800822 const sp<IGraphicBufferProducer>& bufferProducer)
Glenn Kasten11731182011-02-08 17:26:17 -0800823{
Andy McFadden484566c2012-12-18 09:46:54 -0800824 ALOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, bufferProducer.get());
Glenn Kasten11731182011-02-08 17:26:17 -0800825 sp<MediaPlayerBase> p = getPlayer();
826 if (p == 0) return UNKNOWN_ERROR;
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700827
Marco Nelissenf8880202014-11-14 07:58:25 -0800828 sp<IBinder> binder(IInterface::asBinder(bufferProducer));
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700829 if (mConnectedWindowBinder == binder) {
830 return OK;
831 }
832
833 sp<ANativeWindow> anw;
Andy McFadden484566c2012-12-18 09:46:54 -0800834 if (bufferProducer != NULL) {
Marco Nelissenee08f7e2013-09-16 13:30:01 -0700835 anw = new Surface(bufferProducer, true /* controlledByApp */);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700836 status_t err = native_window_api_connect(anw.get(),
837 NATIVE_WINDOW_API_MEDIA);
838
839 if (err != OK) {
Steve Block29357bc2012-01-06 19:20:56 +0000840 ALOGE("setVideoSurfaceTexture failed: %d", err);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700841 // Note that we must do the reset before disconnecting from the ANW.
842 // Otherwise queue/dequeue calls could be made on the disconnected
843 // ANW, which may result in errors.
844 reset();
845
846 disconnectNativeWindow();
847
848 return err;
849 }
850 }
851
Andy McFadden484566c2012-12-18 09:46:54 -0800852 // Note that we must set the player's new GraphicBufferProducer before
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700853 // disconnecting the old one. Otherwise queue/dequeue calls could be made
854 // on the disconnected ANW, which may result in errors.
Andy McFadden484566c2012-12-18 09:46:54 -0800855 status_t err = p->setVideoSurfaceTexture(bufferProducer);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700856
857 disconnectNativeWindow();
858
859 mConnectedWindow = anw;
860
861 if (err == OK) {
862 mConnectedWindowBinder = binder;
863 } else {
864 disconnectNativeWindow();
865 }
866
867 return err;
Glenn Kasten11731182011-02-08 17:26:17 -0800868}
869
Nicolas Catania1d187f12009-05-12 23:25:55 -0700870status_t MediaPlayerService::Client::invoke(const Parcel& request,
871 Parcel *reply)
872{
873 sp<MediaPlayerBase> p = getPlayer();
874 if (p == NULL) return UNKNOWN_ERROR;
875 return p->invoke(request, reply);
876}
877
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700878// This call doesn't need to access the native player.
879status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
880{
881 status_t status;
nikoa64c8c72009-07-20 15:07:26 -0700882 media::Metadata::Filter allow, drop;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700883
Nicolas Catania48290382009-07-10 13:53:06 -0700884 if (unmarshallFilter(filter, &allow, &status) &&
885 unmarshallFilter(filter, &drop, &status)) {
886 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700887
888 mMetadataAllow = allow;
889 mMetadataDrop = drop;
890 }
891 return status;
892}
893
Nicolas Catania48290382009-07-10 13:53:06 -0700894status_t MediaPlayerService::Client::getMetadata(
Mark Salyzyn77342f72014-06-18 16:31:32 -0700895 bool update_only, bool /*apply_filter*/, Parcel *reply)
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700896{
nikoa64c8c72009-07-20 15:07:26 -0700897 sp<MediaPlayerBase> player = getPlayer();
898 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania48290382009-07-10 13:53:06 -0700899
nikod608a812009-07-16 16:39:53 -0700900 status_t status;
901 // Placeholder for the return code, updated by the caller.
902 reply->writeInt32(-1);
903
nikoa64c8c72009-07-20 15:07:26 -0700904 media::Metadata::Filter ids;
Nicolas Catania48290382009-07-10 13:53:06 -0700905
906 // We don't block notifications while we fetch the data. We clear
907 // mMetadataUpdated first so we don't lose notifications happening
908 // during the rest of this call.
909 {
910 Mutex::Autolock lock(mLock);
911 if (update_only) {
nikod608a812009-07-16 16:39:53 -0700912 ids = mMetadataUpdated;
Nicolas Catania48290382009-07-10 13:53:06 -0700913 }
914 mMetadataUpdated.clear();
915 }
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700916
nikoa64c8c72009-07-20 15:07:26 -0700917 media::Metadata metadata(reply);
Nicolas Catania48290382009-07-10 13:53:06 -0700918
nikoa64c8c72009-07-20 15:07:26 -0700919 metadata.appendHeader();
920 status = player->getMetadata(ids, reply);
nikod608a812009-07-16 16:39:53 -0700921
922 if (status != OK) {
nikoa64c8c72009-07-20 15:07:26 -0700923 metadata.resetParcel();
Steve Block29357bc2012-01-06 19:20:56 +0000924 ALOGE("getMetadata failed %d", status);
nikod608a812009-07-16 16:39:53 -0700925 return status;
926 }
927
928 // FIXME: Implement filtering on the result. Not critical since
929 // filtering takes place on the update notifications already. This
930 // would be when all the metadata are fetch and a filter is set.
931
nikod608a812009-07-16 16:39:53 -0700932 // Everything is fine, update the metadata length.
nikoa64c8c72009-07-20 15:07:26 -0700933 metadata.updateLength();
nikod608a812009-07-16 16:39:53 -0700934 return OK;
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700935}
936
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800937status_t MediaPlayerService::Client::prepareAsync()
938{
Steve Block3856b092011-10-20 11:56:00 +0100939 ALOGV("[%d] prepareAsync", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800940 sp<MediaPlayerBase> p = getPlayer();
941 if (p == 0) return UNKNOWN_ERROR;
942 status_t ret = p->prepareAsync();
943#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000944 ALOGD("start Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800945 if (ret == NO_ERROR) mAntagonizer->start();
946#endif
947 return ret;
948}
949
950status_t MediaPlayerService::Client::start()
951{
Steve Block3856b092011-10-20 11:56:00 +0100952 ALOGV("[%d] start", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800953 sp<MediaPlayerBase> p = getPlayer();
954 if (p == 0) return UNKNOWN_ERROR;
955 p->setLooping(mLoop);
956 return p->start();
957}
958
959status_t MediaPlayerService::Client::stop()
960{
Steve Block3856b092011-10-20 11:56:00 +0100961 ALOGV("[%d] stop", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800962 sp<MediaPlayerBase> p = getPlayer();
963 if (p == 0) return UNKNOWN_ERROR;
964 return p->stop();
965}
966
967status_t MediaPlayerService::Client::pause()
968{
Steve Block3856b092011-10-20 11:56:00 +0100969 ALOGV("[%d] pause", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800970 sp<MediaPlayerBase> p = getPlayer();
971 if (p == 0) return UNKNOWN_ERROR;
972 return p->pause();
973}
974
975status_t MediaPlayerService::Client::isPlaying(bool* state)
976{
977 *state = false;
978 sp<MediaPlayerBase> p = getPlayer();
979 if (p == 0) return UNKNOWN_ERROR;
980 *state = p->isPlaying();
Steve Block3856b092011-10-20 11:56:00 +0100981 ALOGV("[%d] isPlaying: %d", mConnId, *state);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800982 return NO_ERROR;
983}
984
Lajos Molnar3a474aa2015-04-24 17:10:07 -0700985status_t MediaPlayerService::Client::setPlaybackSettings(const AudioPlaybackRate& rate)
Wei Jia98160162015-02-04 17:01:11 -0800986{
Lajos Molnar3a474aa2015-04-24 17:10:07 -0700987 ALOGV("[%d] setPlaybackSettings(%f, %f, %d, %d)",
988 mConnId, rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Wei Jia98160162015-02-04 17:01:11 -0800989 sp<MediaPlayerBase> p = getPlayer();
990 if (p == 0) return UNKNOWN_ERROR;
Lajos Molnar3a474aa2015-04-24 17:10:07 -0700991 return p->setPlaybackSettings(rate);
992}
993
994status_t MediaPlayerService::Client::getPlaybackSettings(AudioPlaybackRate* rate /* nonnull */)
995{
996 sp<MediaPlayerBase> p = getPlayer();
997 if (p == 0) return UNKNOWN_ERROR;
998 status_t ret = p->getPlaybackSettings(rate);
999 if (ret == NO_ERROR) {
1000 ALOGV("[%d] getPlaybackSettings(%f, %f, %d, %d)",
1001 mConnId, rate->mSpeed, rate->mPitch, rate->mFallbackMode, rate->mStretchMode);
1002 } else {
1003 ALOGV("[%d] getPlaybackSettings returned %d", mConnId, ret);
1004 }
1005 return ret;
1006}
1007
1008status_t MediaPlayerService::Client::setSyncSettings(
1009 const AVSyncSettings& sync, float videoFpsHint)
1010{
1011 ALOGV("[%d] setSyncSettings(%u, %u, %f, %f)",
1012 mConnId, sync.mSource, sync.mAudioAdjustMode, sync.mTolerance, videoFpsHint);
1013 sp<MediaPlayerBase> p = getPlayer();
1014 if (p == 0) return UNKNOWN_ERROR;
1015 return p->setSyncSettings(sync, videoFpsHint);
1016}
1017
1018status_t MediaPlayerService::Client::getSyncSettings(
1019 AVSyncSettings* sync /* nonnull */, float* videoFps /* nonnull */)
1020{
1021 sp<MediaPlayerBase> p = getPlayer();
1022 if (p == 0) return UNKNOWN_ERROR;
1023 status_t ret = p->getSyncSettings(sync, videoFps);
1024 if (ret == NO_ERROR) {
1025 ALOGV("[%d] getSyncSettings(%u, %u, %f, %f)",
1026 mConnId, sync->mSource, sync->mAudioAdjustMode, sync->mTolerance, *videoFps);
1027 } else {
1028 ALOGV("[%d] getSyncSettings returned %d", mConnId, ret);
1029 }
1030 return ret;
Wei Jia98160162015-02-04 17:01:11 -08001031}
1032
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001033status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
1034{
Steve Block3856b092011-10-20 11:56:00 +01001035 ALOGV("getCurrentPosition");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001036 sp<MediaPlayerBase> p = getPlayer();
1037 if (p == 0) return UNKNOWN_ERROR;
1038 status_t ret = p->getCurrentPosition(msec);
1039 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001040 ALOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001041 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001042 ALOGE("getCurrentPosition returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001043 }
1044 return ret;
1045}
1046
1047status_t MediaPlayerService::Client::getDuration(int *msec)
1048{
Steve Block3856b092011-10-20 11:56:00 +01001049 ALOGV("getDuration");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001050 sp<MediaPlayerBase> p = getPlayer();
1051 if (p == 0) return UNKNOWN_ERROR;
1052 status_t ret = p->getDuration(msec);
1053 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001054 ALOGV("[%d] getDuration = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001055 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001056 ALOGE("getDuration returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001057 }
1058 return ret;
1059}
1060
Marco Nelissen6b74d672012-02-28 16:07:44 -08001061status_t MediaPlayerService::Client::setNextPlayer(const sp<IMediaPlayer>& player) {
1062 ALOGV("setNextPlayer");
1063 Mutex::Autolock l(mLock);
1064 sp<Client> c = static_cast<Client*>(player.get());
1065 mNextClient = c;
John Grossman5f7e55e2012-08-24 14:47:25 -07001066
1067 if (c != NULL) {
1068 if (mAudioOutput != NULL) {
1069 mAudioOutput->setNextOutput(c->mAudioOutput);
1070 } else if ((mPlayer != NULL) && !mPlayer->hardwareOutput()) {
1071 ALOGE("no current audio output");
1072 }
1073
1074 if ((mPlayer != NULL) && (mNextClient->getPlayer() != NULL)) {
1075 mPlayer->setNextPlayer(mNextClient->getPlayer());
1076 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001077 }
John Grossman5f7e55e2012-08-24 14:47:25 -07001078
Marco Nelissen6b74d672012-02-28 16:07:44 -08001079 return OK;
1080}
1081
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001082status_t MediaPlayerService::Client::seekTo(int msec)
1083{
Steve Block3856b092011-10-20 11:56:00 +01001084 ALOGV("[%d] seekTo(%d)", mConnId, msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001085 sp<MediaPlayerBase> p = getPlayer();
1086 if (p == 0) return UNKNOWN_ERROR;
1087 return p->seekTo(msec);
1088}
1089
1090status_t MediaPlayerService::Client::reset()
1091{
Steve Block3856b092011-10-20 11:56:00 +01001092 ALOGV("[%d] reset", mConnId);
John Grossmanc795b642012-02-22 15:38:35 -08001093 mRetransmitEndpointValid = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001094 sp<MediaPlayerBase> p = getPlayer();
1095 if (p == 0) return UNKNOWN_ERROR;
1096 return p->reset();
1097}
1098
Glenn Kastenfff6d712012-01-12 16:38:12 -08001099status_t MediaPlayerService::Client::setAudioStreamType(audio_stream_type_t type)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001100{
Steve Block3856b092011-10-20 11:56:00 +01001101 ALOGV("[%d] setAudioStreamType(%d)", mConnId, type);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001102 // TODO: for hardware output, call player instead
1103 Mutex::Autolock l(mLock);
1104 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1105 return NO_ERROR;
1106}
1107
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001108status_t MediaPlayerService::Client::setAudioAttributes_l(const Parcel &parcel)
1109{
1110 if (mAudioAttributes != NULL) { free(mAudioAttributes); }
1111 mAudioAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001112 if (mAudioAttributes == NULL) {
1113 return NO_MEMORY;
1114 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001115 unmarshallAudioAttributes(parcel, mAudioAttributes);
1116
1117 ALOGV("setAudioAttributes_l() usage=%d content=%d flags=0x%x tags=%s",
1118 mAudioAttributes->usage, mAudioAttributes->content_type, mAudioAttributes->flags,
1119 mAudioAttributes->tags);
1120
1121 if (mAudioOutput != 0) {
1122 mAudioOutput->setAudioAttributes(mAudioAttributes);
1123 }
1124 return NO_ERROR;
1125}
1126
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001127status_t MediaPlayerService::Client::setLooping(int loop)
1128{
Steve Block3856b092011-10-20 11:56:00 +01001129 ALOGV("[%d] setLooping(%d)", mConnId, loop);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001130 mLoop = loop;
1131 sp<MediaPlayerBase> p = getPlayer();
1132 if (p != 0) return p->setLooping(loop);
1133 return NO_ERROR;
1134}
1135
1136status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1137{
Steve Block3856b092011-10-20 11:56:00 +01001138 ALOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
John Grossman761defc2012-02-09 15:09:05 -08001139
1140 // for hardware output, call player instead
1141 sp<MediaPlayerBase> p = getPlayer();
1142 {
1143 Mutex::Autolock l(mLock);
1144 if (p != 0 && p->hardwareOutput()) {
1145 MediaPlayerHWInterface* hwp =
1146 reinterpret_cast<MediaPlayerHWInterface*>(p.get());
1147 return hwp->setVolume(leftVolume, rightVolume);
1148 } else {
1149 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1150 return NO_ERROR;
1151 }
1152 }
1153
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001154 return NO_ERROR;
1155}
1156
Eric Laurent2beeb502010-07-16 07:43:46 -07001157status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1158{
Steve Block3856b092011-10-20 11:56:00 +01001159 ALOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
Eric Laurent2beeb502010-07-16 07:43:46 -07001160 Mutex::Autolock l(mLock);
1161 if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1162 return NO_ERROR;
1163}
1164
1165status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1166{
Steve Block3856b092011-10-20 11:56:00 +01001167 ALOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
Eric Laurent2beeb502010-07-16 07:43:46 -07001168 Mutex::Autolock l(mLock);
1169 if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1170 return NO_ERROR;
1171}
Nicolas Catania48290382009-07-10 13:53:06 -07001172
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001173status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
Steve Block3856b092011-10-20 11:56:00 +01001174 ALOGV("[%d] setParameter(%d)", mConnId, key);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001175 switch (key) {
1176 case KEY_PARAMETER_AUDIO_ATTRIBUTES:
1177 {
1178 Mutex::Autolock l(mLock);
1179 return setAudioAttributes_l(request);
1180 }
1181 default:
1182 sp<MediaPlayerBase> p = getPlayer();
1183 if (p == 0) { return UNKNOWN_ERROR; }
1184 return p->setParameter(key, request);
1185 }
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001186}
1187
1188status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
Steve Block3856b092011-10-20 11:56:00 +01001189 ALOGV("[%d] getParameter(%d)", mConnId, key);
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001190 sp<MediaPlayerBase> p = getPlayer();
1191 if (p == 0) return UNKNOWN_ERROR;
1192 return p->getParameter(key, reply);
1193}
1194
John Grossmanc795b642012-02-22 15:38:35 -08001195status_t MediaPlayerService::Client::setRetransmitEndpoint(
1196 const struct sockaddr_in* endpoint) {
1197
1198 if (NULL != endpoint) {
1199 uint32_t a = ntohl(endpoint->sin_addr.s_addr);
1200 uint16_t p = ntohs(endpoint->sin_port);
1201 ALOGV("[%d] setRetransmitEndpoint(%u.%u.%u.%u:%hu)", mConnId,
1202 (a >> 24), (a >> 16) & 0xFF, (a >> 8) & 0xFF, (a & 0xFF), p);
1203 } else {
1204 ALOGV("[%d] setRetransmitEndpoint = <none>", mConnId);
1205 }
1206
1207 sp<MediaPlayerBase> p = getPlayer();
1208
1209 // Right now, the only valid time to set a retransmit endpoint is before
1210 // player selection has been made (since the presence or absence of a
1211 // retransmit endpoint is going to determine which player is selected during
1212 // setDataSource).
1213 if (p != 0) return INVALID_OPERATION;
1214
1215 if (NULL != endpoint) {
1216 mRetransmitEndpoint = *endpoint;
1217 mRetransmitEndpointValid = true;
1218 } else {
1219 mRetransmitEndpointValid = false;
1220 }
1221
1222 return NO_ERROR;
1223}
1224
John Grossman44a7e422012-06-21 17:29:24 -07001225status_t MediaPlayerService::Client::getRetransmitEndpoint(
1226 struct sockaddr_in* endpoint)
1227{
1228 if (NULL == endpoint)
1229 return BAD_VALUE;
1230
1231 sp<MediaPlayerBase> p = getPlayer();
1232
1233 if (p != NULL)
1234 return p->getRetransmitEndpoint(endpoint);
1235
1236 if (!mRetransmitEndpointValid)
1237 return NO_INIT;
1238
1239 *endpoint = mRetransmitEndpoint;
1240
1241 return NO_ERROR;
1242}
1243
Gloria Wangb483c472011-04-11 17:23:27 -07001244void MediaPlayerService::Client::notify(
1245 void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001246{
1247 Client* client = static_cast<Client*>(cookie);
James Dongb8a98252012-08-26 16:13:03 -07001248 if (client == NULL) {
1249 return;
1250 }
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001251
James Dongb8a98252012-08-26 16:13:03 -07001252 sp<IMediaPlayerClient> c;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001253 {
1254 Mutex::Autolock l(client->mLock);
James Dongb8a98252012-08-26 16:13:03 -07001255 c = client->mClient;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001256 if (msg == MEDIA_PLAYBACK_COMPLETE && client->mNextClient != NULL) {
John Grossmancb0b7552012-08-23 17:47:31 -07001257 if (client->mAudioOutput != NULL)
1258 client->mAudioOutput->switchToNextOutput();
Marco Nelissen6b74d672012-02-28 16:07:44 -08001259 client->mNextClient->start();
Wei Jia2afac0c2016-01-07 12:13:07 -08001260 if (client->mNextClient->mClient != NULL) {
1261 client->mNextClient->mClient->notify(
1262 MEDIA_INFO, MEDIA_INFO_STARTED_AS_NEXT, 0, obj);
1263 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001264 }
1265 }
1266
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001267 if (MEDIA_INFO == msg &&
Nicolas Catania48290382009-07-10 13:53:06 -07001268 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikoa64c8c72009-07-20 15:07:26 -07001269 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania48290382009-07-10 13:53:06 -07001270
1271 if(client->shouldDropMetadata(metadata_type)) {
1272 return;
1273 }
1274
1275 // Update the list of metadata that have changed. getMetadata
1276 // also access mMetadataUpdated and clears it.
1277 client->addNewMetadataUpdate(metadata_type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001278 }
James Dongb8a98252012-08-26 16:13:03 -07001279
1280 if (c != NULL) {
1281 ALOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
1282 c->notify(msg, ext1, ext2, obj);
1283 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001284}
1285
Nicolas Catania48290382009-07-10 13:53:06 -07001286
nikoa64c8c72009-07-20 15:07:26 -07001287bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001288{
Nicolas Catania48290382009-07-10 13:53:06 -07001289 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001290
Nicolas Catania48290382009-07-10 13:53:06 -07001291 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001292 return true;
1293 }
1294
Nicolas Catania48290382009-07-10 13:53:06 -07001295 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001296 return false;
Nicolas Catania48290382009-07-10 13:53:06 -07001297 } else {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001298 return true;
1299 }
1300}
1301
Nicolas Catania48290382009-07-10 13:53:06 -07001302
nikoa64c8c72009-07-20 15:07:26 -07001303void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania48290382009-07-10 13:53:06 -07001304 Mutex::Autolock lock(mLock);
1305 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1306 mMetadataUpdated.add(metadata_type);
1307 }
1308}
1309
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001310#if CALLBACK_ANTAGONIZER
1311const int Antagonizer::interval = 10000; // 10 msecs
1312
1313Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1314 mExit(false), mActive(false), mClient(client), mCb(cb)
1315{
1316 createThread(callbackThread, this);
1317}
1318
1319void Antagonizer::kill()
1320{
1321 Mutex::Autolock _l(mLock);
1322 mActive = false;
1323 mExit = true;
1324 mCondition.wait(mLock);
1325}
1326
1327int Antagonizer::callbackThread(void* user)
1328{
Steve Blockb8a80522011-12-20 16:23:08 +00001329 ALOGD("Antagonizer started");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001330 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1331 while (!p->mExit) {
1332 if (p->mActive) {
Steve Block3856b092011-10-20 11:56:00 +01001333 ALOGV("send event");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001334 p->mCb(p->mClient, 0, 0, 0);
1335 }
1336 usleep(interval);
1337 }
1338 Mutex::Autolock _l(p->mLock);
1339 p->mCondition.signal();
Steve Blockb8a80522011-12-20 16:23:08 +00001340 ALOGD("Antagonizer stopped");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001341 return 0;
1342}
1343#endif
1344
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001345#undef LOG_TAG
1346#define LOG_TAG "AudioSink"
Glenn Kastend848eb42016-03-08 13:42:11 -08001347MediaPlayerService::AudioOutput::AudioOutput(audio_session_t sessionId, int uid, int pid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001348 const audio_attributes_t* attr)
Andreas Huber20111aa2009-07-14 16:56:47 -07001349 : mCallback(NULL),
Eric Laurenta514bdb2010-06-21 09:27:30 -07001350 mCallbackCookie(NULL),
Marco Nelissen6b74d672012-02-28 16:07:44 -08001351 mCallbackData(NULL),
Andy Hungd1c74342015-07-07 16:54:23 -07001352 mStreamType(AUDIO_STREAM_MUSIC),
Andy Hungd1c74342015-07-07 16:54:23 -07001353 mLeftVolume(1.0),
1354 mRightVolume(1.0),
1355 mPlaybackRate(AUDIO_PLAYBACK_RATE_DEFAULT),
1356 mSampleRateHz(0),
1357 mMsecsPerFrame(0),
1358 mFrameSize(0),
Eric Laurent1948eb32012-04-13 16:50:19 -07001359 mSessionId(sessionId),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001360 mUid(uid),
Marco Nelissend457c972014-02-11 08:47:07 -08001361 mPid(pid),
Andy Hungd1c74342015-07-07 16:54:23 -07001362 mSendLevel(0.0),
1363 mAuxEffectId(0),
1364 mFlags(AUDIO_OUTPUT_FLAG_NONE)
1365{
Steve Block3856b092011-10-20 11:56:00 +01001366 ALOGV("AudioOutput(%d)", sessionId);
Eric Laurent43562692015-07-15 16:49:07 -07001367 if (attr != NULL) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001368 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1369 if (mAttributes != NULL) {
1370 memcpy(mAttributes, attr, sizeof(audio_attributes_t));
1371 mStreamType = audio_attributes_to_stream_type(attr);
1372 }
1373 } else {
1374 mAttributes = NULL;
Eric Laurent43562692015-07-15 16:49:07 -07001375 }
1376
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001377 setMinBufferCount();
1378}
1379
1380MediaPlayerService::AudioOutput::~AudioOutput()
1381{
1382 close();
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001383 free(mAttributes);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001384 delete mCallbackData;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001385}
1386
Andy Hungd1c74342015-07-07 16:54:23 -07001387//static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001388void MediaPlayerService::AudioOutput::setMinBufferCount()
1389{
1390 char value[PROPERTY_VALUE_MAX];
1391 if (property_get("ro.kernel.qemu", value, 0)) {
1392 mIsOnEmulator = true;
1393 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1394 }
1395}
1396
Andy Hungd1c74342015-07-07 16:54:23 -07001397// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001398bool MediaPlayerService::AudioOutput::isOnEmulator()
1399{
Andy Hungd1c74342015-07-07 16:54:23 -07001400 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001401 return mIsOnEmulator;
1402}
1403
Andy Hungd1c74342015-07-07 16:54:23 -07001404// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001405int MediaPlayerService::AudioOutput::getMinBufferCount()
1406{
Andy Hungd1c74342015-07-07 16:54:23 -07001407 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001408 return mMinBufferCount;
1409}
1410
1411ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1412{
Andy Hungd1c74342015-07-07 16:54:23 -07001413 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001414 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001415 return mTrack->frameCount() * mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001416}
1417
1418ssize_t MediaPlayerService::AudioOutput::frameCount() const
1419{
Andy Hungd1c74342015-07-07 16:54:23 -07001420 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001421 if (mTrack == 0) return NO_INIT;
1422 return mTrack->frameCount();
1423}
1424
1425ssize_t MediaPlayerService::AudioOutput::channelCount() const
1426{
Andy Hungd1c74342015-07-07 16:54:23 -07001427 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001428 if (mTrack == 0) return NO_INIT;
1429 return mTrack->channelCount();
1430}
1431
1432ssize_t MediaPlayerService::AudioOutput::frameSize() const
1433{
Andy Hungd1c74342015-07-07 16:54:23 -07001434 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001435 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001436 return mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001437}
1438
1439uint32_t MediaPlayerService::AudioOutput::latency () const
1440{
Andy Hungd1c74342015-07-07 16:54:23 -07001441 Mutex::Autolock lock(mLock);
Eric Laurentdb354e52012-03-05 17:27:11 -08001442 if (mTrack == 0) return 0;
1443 return mTrack->latency();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001444}
1445
1446float MediaPlayerService::AudioOutput::msecsPerFrame() const
1447{
Andy Hungd1c74342015-07-07 16:54:23 -07001448 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001449 return mMsecsPerFrame;
1450}
1451
Marco Nelissen4110c102012-03-29 09:31:28 -07001452status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position) const
Eric Laurent342e9cf2010-01-19 17:37:09 -08001453{
Andy Hungd1c74342015-07-07 16:54:23 -07001454 Mutex::Autolock lock(mLock);
Eric Laurent342e9cf2010-01-19 17:37:09 -08001455 if (mTrack == 0) return NO_INIT;
1456 return mTrack->getPosition(position);
1457}
1458
Lajos Molnar06ad1522014-08-28 07:27:44 -07001459status_t MediaPlayerService::AudioOutput::getTimestamp(AudioTimestamp &ts) const
1460{
Andy Hungd1c74342015-07-07 16:54:23 -07001461 Mutex::Autolock lock(mLock);
Lajos Molnar06ad1522014-08-28 07:27:44 -07001462 if (mTrack == 0) return NO_INIT;
1463 return mTrack->getTimestamp(ts);
1464}
1465
Wei Jiac4ac8172015-10-21 10:35:48 -07001466// TODO: Remove unnecessary calls to getPlayedOutDurationUs()
1467// as it acquires locks and may query the audio driver.
1468//
1469// Some calls could conceivably retrieve extrapolated data instead of
1470// accessing getTimestamp() or getPosition() every time a data buffer with
1471// a media time is received.
1472//
1473// Calculate duration of played samples if played at normal rate (i.e., 1.0).
1474int64_t MediaPlayerService::AudioOutput::getPlayedOutDurationUs(int64_t nowUs) const
1475{
1476 Mutex::Autolock lock(mLock);
1477 if (mTrack == 0 || mSampleRateHz == 0) {
Wei Jia213f4902015-10-22 08:55:25 -07001478 return 0;
Wei Jiac4ac8172015-10-21 10:35:48 -07001479 }
1480
1481 uint32_t numFramesPlayed;
1482 int64_t numFramesPlayedAt;
1483 AudioTimestamp ts;
1484 static const int64_t kStaleTimestamp100ms = 100000;
1485
1486 status_t res = mTrack->getTimestamp(ts);
1487 if (res == OK) { // case 1: mixing audio tracks and offloaded tracks.
1488 numFramesPlayed = ts.mPosition;
1489 numFramesPlayedAt = ts.mTime.tv_sec * 1000000LL + ts.mTime.tv_nsec / 1000;
1490 const int64_t timestampAge = nowUs - numFramesPlayedAt;
1491 if (timestampAge > kStaleTimestamp100ms) {
1492 // This is an audio FIXME.
1493 // getTimestamp returns a timestamp which may come from audio mixing threads.
1494 // After pausing, the MixerThread may go idle, thus the mTime estimate may
1495 // become stale. Assuming that the MixerThread runs 20ms, with FastMixer at 5ms,
1496 // the max latency should be about 25ms with an average around 12ms (to be verified).
1497 // For safety we use 100ms.
1498 ALOGV("getTimestamp: returned stale timestamp nowUs(%lld) numFramesPlayedAt(%lld)",
1499 (long long)nowUs, (long long)numFramesPlayedAt);
1500 numFramesPlayedAt = nowUs - kStaleTimestamp100ms;
1501 }
1502 //ALOGD("getTimestamp: OK %d %lld", numFramesPlayed, (long long)numFramesPlayedAt);
1503 } else if (res == WOULD_BLOCK) { // case 2: transitory state on start of a new track
1504 numFramesPlayed = 0;
1505 numFramesPlayedAt = nowUs;
1506 //ALOGD("getTimestamp: WOULD_BLOCK %d %lld",
1507 // numFramesPlayed, (long long)numFramesPlayedAt);
1508 } else { // case 3: transitory at new track or audio fast tracks.
1509 res = mTrack->getPosition(&numFramesPlayed);
1510 CHECK_EQ(res, (status_t)OK);
1511 numFramesPlayedAt = nowUs;
1512 numFramesPlayedAt += 1000LL * mTrack->latency() / 2; /* XXX */
1513 //ALOGD("getPosition: %u %lld", numFramesPlayed, (long long)numFramesPlayedAt);
1514 }
1515
1516 // CHECK_EQ(numFramesPlayed & (1 << 31), 0); // can't be negative until 12.4 hrs, test
1517 // TODO: remove the (int32_t) casting below as it may overflow at 12.4 hours.
1518 int64_t durationUs = (int64_t)((int32_t)numFramesPlayed * 1000000LL / mSampleRateHz)
1519 + nowUs - numFramesPlayedAt;
1520 if (durationUs < 0) {
1521 // Occurs when numFramesPlayed position is very small and the following:
1522 // (1) In case 1, the time nowUs is computed before getTimestamp() is called and
1523 // numFramesPlayedAt is greater than nowUs by time more than numFramesPlayed.
1524 // (2) In case 3, using getPosition and adding mAudioSink->latency() to
1525 // numFramesPlayedAt, by a time amount greater than numFramesPlayed.
1526 //
1527 // Both of these are transitory conditions.
1528 ALOGV("getPlayedOutDurationUs: negative duration %lld set to zero", (long long)durationUs);
1529 durationUs = 0;
1530 }
1531 ALOGV("getPlayedOutDurationUs(%lld) nowUs(%lld) frames(%u) framesAt(%lld)",
1532 (long long)durationUs, (long long)nowUs, numFramesPlayed, (long long)numFramesPlayedAt);
1533 return durationUs;
1534}
1535
Marco Nelissen4110c102012-03-29 09:31:28 -07001536status_t MediaPlayerService::AudioOutput::getFramesWritten(uint32_t *frameswritten) const
1537{
Andy Hungd1c74342015-07-07 16:54:23 -07001538 Mutex::Autolock lock(mLock);
Marco Nelissen4110c102012-03-29 09:31:28 -07001539 if (mTrack == 0) return NO_INIT;
Andy Hung2f6e73d2016-04-08 12:12:58 -07001540 ExtendedTimestamp ets;
1541 status_t status = mTrack->getTimestamp(&ets);
1542 if (status == OK || status == WOULD_BLOCK) {
1543 *frameswritten = (uint32_t)ets.mPosition[ExtendedTimestamp::LOCATION_CLIENT];
1544 }
1545 return status;
Marco Nelissen4110c102012-03-29 09:31:28 -07001546}
1547
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001548status_t MediaPlayerService::AudioOutput::setParameters(const String8& keyValuePairs)
1549{
Andy Hungd1c74342015-07-07 16:54:23 -07001550 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001551 if (mTrack == 0) return NO_INIT;
1552 return mTrack->setParameters(keyValuePairs);
1553}
1554
1555String8 MediaPlayerService::AudioOutput::getParameters(const String8& keys)
1556{
Andy Hungd1c74342015-07-07 16:54:23 -07001557 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001558 if (mTrack == 0) return String8::empty();
1559 return mTrack->getParameters(keys);
1560}
1561
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001562void MediaPlayerService::AudioOutput::setAudioAttributes(const audio_attributes_t * attributes) {
Andy Hungd1c74342015-07-07 16:54:23 -07001563 Mutex::Autolock lock(mLock);
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001564 if (attributes == NULL) {
1565 free(mAttributes);
1566 mAttributes = NULL;
1567 } else {
1568 if (mAttributes == NULL) {
1569 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1570 }
1571 memcpy(mAttributes, attributes, sizeof(audio_attributes_t));
Eric Laurent43562692015-07-15 16:49:07 -07001572 mStreamType = audio_attributes_to_stream_type(attributes);
1573 }
1574}
1575
1576void MediaPlayerService::AudioOutput::setAudioStreamType(audio_stream_type_t streamType)
1577{
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001578 Mutex::Autolock lock(mLock);
Eric Laurent43562692015-07-15 16:49:07 -07001579 // do not allow direct stream type modification if attributes have been set
1580 if (mAttributes == NULL) {
1581 mStreamType = streamType;
1582 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001583}
1584
Andy Hungd1c74342015-07-07 16:54:23 -07001585void MediaPlayerService::AudioOutput::deleteRecycledTrack_l()
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001586{
Andy Hungd1c74342015-07-07 16:54:23 -07001587 ALOGV("deleteRecycledTrack_l");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001588 if (mRecycledTrack != 0) {
1589
1590 if (mCallbackData != NULL) {
1591 mCallbackData->setOutput(NULL);
1592 mCallbackData->endTrackSwitch();
1593 }
1594
1595 if ((mRecycledTrack->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) {
Andy Hunge13f8a62016-03-30 14:20:42 -07001596 int32_t msec = 0;
1597 if (!mRecycledTrack->stopped()) { // check if active
1598 (void)mRecycledTrack->pendingDuration(&msec);
1599 }
1600 mRecycledTrack->stop(); // ensure full data drain
1601 ALOGD("deleting recycled track, waiting for data drain (%d msec)", msec);
1602 if (msec > 0) {
1603 static const int32_t WAIT_LIMIT_MS = 3000;
1604 if (msec > WAIT_LIMIT_MS) {
1605 msec = WAIT_LIMIT_MS;
1606 }
1607 usleep(msec * 1000LL);
1608 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001609 }
1610 // An offloaded track isn't flushed because the STREAM_END is reported
1611 // slightly prematurely to allow time for the gapless track switch
1612 // but this means that if we decide not to recycle the track there
1613 // could be a small amount of residual data still playing. We leave
1614 // AudioFlinger to drain the track.
1615
1616 mRecycledTrack.clear();
Andy Hungd1c74342015-07-07 16:54:23 -07001617 close_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001618 delete mCallbackData;
1619 mCallbackData = NULL;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001620 }
1621}
1622
Andy Hungd1c74342015-07-07 16:54:23 -07001623void MediaPlayerService::AudioOutput::close_l()
1624{
1625 mTrack.clear();
1626}
1627
Andreas Huber20111aa2009-07-14 16:56:47 -07001628status_t MediaPlayerService::AudioOutput::open(
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001629 uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
1630 audio_format_t format, int bufferCount,
Eric Laurent1948eb32012-04-13 16:50:19 -07001631 AudioCallback cb, void *cookie,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001632 audio_output_flags_t flags,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001633 const audio_offload_info_t *offloadInfo,
Andy Hung179652e2015-05-31 22:49:46 -07001634 bool doNotReconnect,
1635 uint32_t suggestedFrameCount)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001636{
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001637 ALOGV("open(%u, %d, 0x%x, 0x%x, %d, %d 0x%x)", sampleRate, channelCount, channelMask,
1638 format, bufferCount, mSessionId, flags);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001639
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001640 // offloading is only supported in callback mode for now.
1641 // offloadInfo must be present if offload flag is set
1642 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) &&
1643 ((cb == NULL) || (offloadInfo == NULL))) {
1644 return BAD_VALUE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001645 }
1646
Andy Hung179652e2015-05-31 22:49:46 -07001647 // compute frame count for the AudioTrack internal buffer
1648 size_t frameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001649 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1650 frameCount = 0; // AudioTrack will get frame count from AudioFlinger
1651 } else {
Andy Hung179652e2015-05-31 22:49:46 -07001652 // try to estimate the buffer processing fetch size from AudioFlinger.
1653 // framesPerBuffer is approximate and generally correct, except when it's not :-).
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001654 uint32_t afSampleRate;
1655 size_t afFrameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001656 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1657 return NO_INIT;
1658 }
1659 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1660 return NO_INIT;
1661 }
Andy Hung179652e2015-05-31 22:49:46 -07001662 const size_t framesPerBuffer =
1663 (unsigned long long)sampleRate * afFrameCount / afSampleRate;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001664
Andy Hung179652e2015-05-31 22:49:46 -07001665 if (bufferCount == 0) {
1666 // use suggestedFrameCount
1667 bufferCount = (suggestedFrameCount + framesPerBuffer - 1) / framesPerBuffer;
1668 }
1669 // Check argument bufferCount against the mininum buffer count
1670 if (bufferCount != 0 && bufferCount < mMinBufferCount) {
1671 ALOGV("bufferCount (%d) increased to %d", bufferCount, mMinBufferCount);
1672 bufferCount = mMinBufferCount;
1673 }
1674 // if frameCount is 0, then AudioTrack will get frame count from AudioFlinger
1675 // which will be the minimum size permitted.
1676 frameCount = bufferCount * framesPerBuffer;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001677 }
Andreas Huber20111aa2009-07-14 16:56:47 -07001678
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001679 if (channelMask == CHANNEL_MASK_USE_CHANNEL_ORDER) {
Glenn Kastenab334fd2012-03-14 12:56:06 -07001680 channelMask = audio_channel_out_mask_from_count(channelCount);
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001681 if (0 == channelMask) {
1682 ALOGE("open() error, can\'t derive mask for %d audio channels", channelCount);
1683 return NO_INIT;
1684 }
1685 }
Eric Laurent1948eb32012-04-13 16:50:19 -07001686
Andy Hungd1c74342015-07-07 16:54:23 -07001687 Mutex::Autolock lock(mLock);
Andy Hung179652e2015-05-31 22:49:46 -07001688 mCallback = cb;
1689 mCallbackCookie = cookie;
1690
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001691 // Check whether we can recycle the track
1692 bool reuse = false;
1693 bool bothOffloaded = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001694
Glenn Kasten2799d742013-05-30 14:33:29 -07001695 if (mRecycledTrack != 0) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001696 // check whether we are switching between two offloaded tracks
1697 bothOffloaded = (flags & mRecycledTrack->getFlags()
1698 & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0;
Marco Nelissen67295b52012-06-11 14:52:53 -07001699
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001700 // check if the existing track can be reused as-is, or if a new track needs to be created.
1701 reuse = true;
1702
Marco Nelissen67295b52012-06-11 14:52:53 -07001703 if ((mCallbackData == NULL && mCallback != NULL) ||
1704 (mCallbackData != NULL && mCallback == NULL)) {
1705 // recycled track uses callbacks but the caller wants to use writes, or vice versa
1706 ALOGV("can't chain callback and write");
1707 reuse = false;
1708 } else if ((mRecycledTrack->getSampleRate() != sampleRate) ||
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001709 (mRecycledTrack->channelCount() != (uint32_t)channelCount) ) {
1710 ALOGV("samplerate, channelcount differ: %u/%u Hz, %u/%d ch",
Marco Nelissen67295b52012-06-11 14:52:53 -07001711 mRecycledTrack->getSampleRate(), sampleRate,
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001712 mRecycledTrack->channelCount(), channelCount);
Marco Nelissen67295b52012-06-11 14:52:53 -07001713 reuse = false;
1714 } else if (flags != mFlags) {
1715 ALOGV("output flags differ %08x/%08x", flags, mFlags);
1716 reuse = false;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001717 } else if (mRecycledTrack->format() != format) {
1718 reuse = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001719 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001720 } else {
1721 ALOGV("no track available to recycle");
1722 }
1723
1724 ALOGV_IF(bothOffloaded, "both tracks offloaded");
1725
1726 // If we can't recycle and both tracks are offloaded
1727 // we must close the previous output before opening a new one
1728 if (bothOffloaded && !reuse) {
1729 ALOGV("both offloaded and not recycling");
Andy Hungd1c74342015-07-07 16:54:23 -07001730 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001731 }
1732
1733 sp<AudioTrack> t;
1734 CallbackData *newcbd = NULL;
1735
1736 // We don't attempt to create a new track if we are recycling an
1737 // offloaded track. But, if we are recycling a non-offloaded or we
1738 // are switching where one is offloaded and one isn't then we create
1739 // the new track in advance so that we can read additional stream info
1740
1741 if (!(reuse && bothOffloaded)) {
1742 ALOGV("creating new AudioTrack");
1743
1744 if (mCallback != NULL) {
1745 newcbd = new CallbackData(this);
1746 t = new AudioTrack(
1747 mStreamType,
1748 sampleRate,
1749 format,
1750 channelMask,
1751 frameCount,
1752 flags,
1753 CallbackWrapper,
1754 newcbd,
1755 0, // notification frames
1756 mSessionId,
1757 AudioTrack::TRANSFER_CALLBACK,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001758 offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -08001759 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001760 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001761 mAttributes,
1762 doNotReconnect);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001763 } else {
Andy Hungff874dc2016-04-11 16:49:09 -07001764 // TODO: Due to buffer memory concerns, we use a max target playback speed
1765 // based on mPlaybackRate at the time of open (instead of kMaxRequiredSpeed),
1766 // also clamping the target speed to 1.0 <= targetSpeed <= kMaxRequiredSpeed.
1767 const float targetSpeed =
1768 std::min(std::max(mPlaybackRate.mSpeed, 1.0f), kMaxRequiredSpeed);
1769 ALOGW_IF(targetSpeed != mPlaybackRate.mSpeed,
1770 "track target speed:%f clamped from playback speed:%f",
1771 targetSpeed, mPlaybackRate.mSpeed);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001772 t = new AudioTrack(
1773 mStreamType,
1774 sampleRate,
1775 format,
1776 channelMask,
1777 frameCount,
1778 flags,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001779 NULL, // callback
1780 NULL, // user data
1781 0, // notification frames
1782 mSessionId,
1783 AudioTrack::TRANSFER_DEFAULT,
1784 NULL, // offload info
Marco Nelissend457c972014-02-11 08:47:07 -08001785 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001786 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001787 mAttributes,
Andy Hungff874dc2016-04-11 16:49:09 -07001788 doNotReconnect,
1789 targetSpeed);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001790 }
1791
1792 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1793 ALOGE("Unable to create audio track");
1794 delete newcbd;
Glenn Kasten3e98ecd2015-05-18 13:13:24 -07001795 // t goes out of scope, so reference count drops to zero
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001796 return NO_INIT;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001797 } else {
1798 // successful AudioTrack initialization implies a legacy stream type was generated
1799 // from the audio attributes
1800 mStreamType = t->streamType();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001801 }
1802 }
1803
1804 if (reuse) {
1805 CHECK(mRecycledTrack != NULL);
1806
1807 if (!bothOffloaded) {
1808 if (mRecycledTrack->frameCount() != t->frameCount()) {
Andy Hung833b4752016-04-04 17:15:48 -07001809 ALOGV("framecount differs: %zu/%zu frames",
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001810 mRecycledTrack->frameCount(), t->frameCount());
1811 reuse = false;
1812 }
1813 }
1814
Marco Nelissen67295b52012-06-11 14:52:53 -07001815 if (reuse) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001816 ALOGV("chaining to next output and recycling track");
Andy Hungd1c74342015-07-07 16:54:23 -07001817 close_l();
Marco Nelissen67295b52012-06-11 14:52:53 -07001818 mTrack = mRecycledTrack;
Glenn Kasten2799d742013-05-30 14:33:29 -07001819 mRecycledTrack.clear();
Marco Nelissen67295b52012-06-11 14:52:53 -07001820 if (mCallbackData != NULL) {
1821 mCallbackData->setOutput(this);
1822 }
Marco Nelissen67295b52012-06-11 14:52:53 -07001823 delete newcbd;
1824 return OK;
1825 }
Marco Nelissen67295b52012-06-11 14:52:53 -07001826 }
1827
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001828 // we're not going to reuse the track, unblock and flush it
1829 // this was done earlier if both tracks are offloaded
1830 if (!bothOffloaded) {
Andy Hungd1c74342015-07-07 16:54:23 -07001831 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001832 }
1833
1834 CHECK((t != NULL) && ((mCallback == NULL) || (newcbd != NULL)));
1835
Marco Nelissen67295b52012-06-11 14:52:53 -07001836 mCallbackData = newcbd;
Steve Block3856b092011-10-20 11:56:00 +01001837 ALOGV("setVolume");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001838 t->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07001839
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001840 mSampleRateHz = sampleRate;
Preetam Singh Ranawat2e17eef2015-08-12 12:11:46 -07001841 mFlags = flags;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001842 mMsecsPerFrame = 1E3f / (mPlaybackRate.mSpeed * sampleRate);
Andy Hungd1c74342015-07-07 16:54:23 -07001843 mFrameSize = t->frameSize();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001844 mTrack = t;
Eric Laurent2beeb502010-07-16 07:43:46 -07001845
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001846 status_t res = NO_ERROR;
Wei Jia0162d002015-06-09 11:59:33 -07001847 // Note some output devices may give us a direct track even though we don't specify it.
1848 // Example: Line application b/17459982.
Preetam Singh Ranawat2e17eef2015-08-12 12:11:46 -07001849 if ((t->getFlags() & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) {
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001850 res = t->setPlaybackRate(mPlaybackRate);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001851 if (res == NO_ERROR) {
1852 t->setAuxEffectSendLevel(mSendLevel);
1853 res = t->attachAuxEffect(mAuxEffectId);
1854 }
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001855 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001856 ALOGV("open() DONE status %d", res);
1857 return res;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001858}
1859
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001860status_t MediaPlayerService::AudioOutput::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001861{
Steve Block3856b092011-10-20 11:56:00 +01001862 ALOGV("start");
Andy Hungd1c74342015-07-07 16:54:23 -07001863 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001864 if (mCallbackData != NULL) {
1865 mCallbackData->endTrackSwitch();
1866 }
Glenn Kasten2799d742013-05-30 14:33:29 -07001867 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001868 mTrack->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07001869 mTrack->setAuxEffectSendLevel(mSendLevel);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001870 return mTrack->start();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001871 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001872 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001873}
1874
Marco Nelissen6b74d672012-02-28 16:07:44 -08001875void MediaPlayerService::AudioOutput::setNextOutput(const sp<AudioOutput>& nextOutput) {
Andy Hungd1c74342015-07-07 16:54:23 -07001876 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001877 mNextOutput = nextOutput;
1878}
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08001879
Marco Nelissen6b74d672012-02-28 16:07:44 -08001880void MediaPlayerService::AudioOutput::switchToNextOutput() {
1881 ALOGV("switchToNextOutput");
Andy Hungd1c74342015-07-07 16:54:23 -07001882
1883 // Try to acquire the callback lock before moving track (without incurring deadlock).
1884 const unsigned kMaxSwitchTries = 100;
1885 Mutex::Autolock lock(mLock);
1886 for (unsigned tries = 0;;) {
1887 if (mTrack == 0) {
1888 return;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001889 }
Andy Hungd1c74342015-07-07 16:54:23 -07001890 if (mNextOutput != NULL && mNextOutput != this) {
1891 if (mCallbackData != NULL) {
1892 // two alternative approaches
1893#if 1
1894 CallbackData *callbackData = mCallbackData;
1895 mLock.unlock();
1896 // proper acquisition sequence
1897 callbackData->lock();
1898 mLock.lock();
1899 // Caution: it is unlikely that someone deleted our callback or changed our target
1900 if (callbackData != mCallbackData || mNextOutput == NULL || mNextOutput == this) {
1901 // fatal if we are starved out.
1902 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
1903 "switchToNextOutput() cannot obtain correct lock sequence");
1904 callbackData->unlock();
1905 continue;
1906 }
1907 callbackData->mSwitching = true; // begin track switch
1908#else
1909 // tryBeginTrackSwitch() returns false if the callback has the lock.
1910 if (!mCallbackData->tryBeginTrackSwitch()) {
1911 // fatal if we are starved out.
1912 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
1913 "switchToNextOutput() cannot obtain callback lock");
1914 mLock.unlock();
1915 usleep(5 * 1000 /* usec */); // allow callback to use AudioOutput
1916 mLock.lock();
1917 continue;
1918 }
1919#endif
1920 }
1921
1922 Mutex::Autolock nextLock(mNextOutput->mLock);
1923
1924 // If the next output track is not NULL, then it has been
1925 // opened already for playback.
1926 // This is possible even without the next player being started,
1927 // for example, the next player could be prepared and seeked.
1928 //
1929 // Presuming it isn't advisable to force the track over.
1930 if (mNextOutput->mTrack == NULL) {
1931 ALOGD("Recycling track for gapless playback");
1932 delete mNextOutput->mCallbackData;
1933 mNextOutput->mCallbackData = mCallbackData;
1934 mNextOutput->mRecycledTrack = mTrack;
1935 mNextOutput->mSampleRateHz = mSampleRateHz;
1936 mNextOutput->mMsecsPerFrame = mMsecsPerFrame;
Andy Hungd1c74342015-07-07 16:54:23 -07001937 mNextOutput->mFlags = mFlags;
1938 mNextOutput->mFrameSize = mFrameSize;
1939 close_l();
1940 mCallbackData = NULL; // destruction handled by mNextOutput
1941 } else {
1942 ALOGW("Ignoring gapless playback because next player has already started");
1943 // remove track in case resource needed for future players.
1944 if (mCallbackData != NULL) {
1945 mCallbackData->endTrackSwitch(); // release lock for callbacks before close.
1946 }
1947 close_l();
1948 }
1949 }
1950 break;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001951 }
1952}
1953
Wei Jia7d3f4df2015-03-03 15:28:00 -08001954ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001955{
Andy Hungd1c74342015-07-07 16:54:23 -07001956 Mutex::Autolock lock(mLock);
Glenn Kastenadad3d72014-02-21 14:51:43 -08001957 LOG_ALWAYS_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
Andreas Huber20111aa2009-07-14 16:56:47 -07001958
Steve Block3856b092011-10-20 11:56:00 +01001959 //ALOGV("write(%p, %u)", buffer, size);
Glenn Kasten2799d742013-05-30 14:33:29 -07001960 if (mTrack != 0) {
Andy Hung2f6e73d2016-04-08 12:12:58 -07001961 return mTrack->write(buffer, size, blocking);
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001962 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001963 return NO_INIT;
1964}
1965
1966void MediaPlayerService::AudioOutput::stop()
1967{
Steve Block3856b092011-10-20 11:56:00 +01001968 ALOGV("stop");
Andy Hungd1c74342015-07-07 16:54:23 -07001969 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07001970 if (mTrack != 0) mTrack->stop();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001971}
1972
1973void MediaPlayerService::AudioOutput::flush()
1974{
Steve Block3856b092011-10-20 11:56:00 +01001975 ALOGV("flush");
Andy Hungd1c74342015-07-07 16:54:23 -07001976 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07001977 if (mTrack != 0) mTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001978}
1979
1980void MediaPlayerService::AudioOutput::pause()
1981{
Steve Block3856b092011-10-20 11:56:00 +01001982 ALOGV("pause");
Andy Hungd1c74342015-07-07 16:54:23 -07001983 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07001984 if (mTrack != 0) mTrack->pause();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001985}
1986
1987void MediaPlayerService::AudioOutput::close()
1988{
Steve Block3856b092011-10-20 11:56:00 +01001989 ALOGV("close");
Erik Wolsheimer7845a1f2015-10-30 12:07:52 -07001990 sp<AudioTrack> track;
1991 {
1992 Mutex::Autolock lock(mLock);
1993 track = mTrack;
1994 close_l(); // clears mTrack
1995 }
1996 // destruction of the track occurs outside of mutex.
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001997}
1998
1999void MediaPlayerService::AudioOutput::setVolume(float left, float right)
2000{
Steve Block3856b092011-10-20 11:56:00 +01002001 ALOGV("setVolume(%f, %f)", left, right);
Andy Hungd1c74342015-07-07 16:54:23 -07002002 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002003 mLeftVolume = left;
2004 mRightVolume = right;
Glenn Kasten2799d742013-05-30 14:33:29 -07002005 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002006 mTrack->setVolume(left, right);
2007 }
2008}
2009
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002010status_t MediaPlayerService::AudioOutput::setPlaybackRate(const AudioPlaybackRate &rate)
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002011{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002012 ALOGV("setPlaybackRate(%f %f %d %d)",
2013 rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Andy Hungd1c74342015-07-07 16:54:23 -07002014 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002015 if (mTrack == 0) {
2016 // remember rate so that we can set it when the track is opened
2017 mPlaybackRate = rate;
2018 return OK;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002019 }
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002020 status_t res = mTrack->setPlaybackRate(rate);
2021 if (res != NO_ERROR) {
2022 return res;
2023 }
2024 // rate.mSpeed is always greater than 0 if setPlaybackRate succeeded
2025 CHECK_GT(rate.mSpeed, 0.f);
2026 mPlaybackRate = rate;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002027 if (mSampleRateHz != 0) {
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002028 mMsecsPerFrame = 1E3f / (rate.mSpeed * mSampleRateHz);
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002029 }
2030 return res;
2031}
2032
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002033status_t MediaPlayerService::AudioOutput::getPlaybackRate(AudioPlaybackRate *rate)
2034{
2035 ALOGV("setPlaybackRate");
Andy Hungd1c74342015-07-07 16:54:23 -07002036 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002037 if (mTrack == 0) {
2038 return NO_INIT;
2039 }
2040 *rate = mTrack->getPlaybackRate();
2041 return NO_ERROR;
2042}
2043
Eric Laurent2beeb502010-07-16 07:43:46 -07002044status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
2045{
Steve Block3856b092011-10-20 11:56:00 +01002046 ALOGV("setAuxEffectSendLevel(%f)", level);
Andy Hungd1c74342015-07-07 16:54:23 -07002047 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002048 mSendLevel = level;
Glenn Kasten2799d742013-05-30 14:33:29 -07002049 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002050 return mTrack->setAuxEffectSendLevel(level);
2051 }
2052 return NO_ERROR;
2053}
2054
2055status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
2056{
Steve Block3856b092011-10-20 11:56:00 +01002057 ALOGV("attachAuxEffect(%d)", effectId);
Andy Hungd1c74342015-07-07 16:54:23 -07002058 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002059 mAuxEffectId = effectId;
Glenn Kasten2799d742013-05-30 14:33:29 -07002060 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002061 return mTrack->attachAuxEffect(effectId);
2062 }
2063 return NO_ERROR;
2064}
2065
Andreas Huber20111aa2009-07-14 16:56:47 -07002066// static
2067void MediaPlayerService::AudioOutput::CallbackWrapper(
Glenn Kastend217a8c2011-06-01 15:20:35 -07002068 int event, void *cookie, void *info) {
Steve Block3856b092011-10-20 11:56:00 +01002069 //ALOGV("callbackwrapper");
Marco Nelissen6b74d672012-02-28 16:07:44 -08002070 CallbackData *data = (CallbackData*)cookie;
Andy Hungd1c74342015-07-07 16:54:23 -07002071 // lock to ensure we aren't caught in the middle of a track switch.
Marco Nelissen6b74d672012-02-28 16:07:44 -08002072 data->lock();
2073 AudioOutput *me = data->getOutput();
Andreas Huber20111aa2009-07-14 16:56:47 -07002074 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002075 if (me == NULL) {
2076 // no output set, likely because the track was scheduled to be reused
2077 // by another player, but the format turned out to be incompatible.
2078 data->unlock();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002079 if (buffer != NULL) {
2080 buffer->size = 0;
2081 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08002082 return;
2083 }
Andreas Huber20111aa2009-07-14 16:56:47 -07002084
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002085 switch(event) {
2086 case AudioTrack::EVENT_MORE_DATA: {
2087 size_t actualSize = (*me->mCallback)(
2088 me, buffer->raw, buffer->size, me->mCallbackCookie,
2089 CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002090
Andy Hung719b46b2015-05-31 22:18:25 -07002091 // Log when no data is returned from the callback.
2092 // (1) We may have no data (especially with network streaming sources).
2093 // (2) We may have reached the EOS and the audio track is not stopped yet.
2094 // Note that AwesomePlayer/AudioPlayer will only return zero size when it reaches the EOS.
2095 // NuPlayerRenderer will return zero when it doesn't have data (it doesn't block to fill).
2096 //
2097 // This is a benign busy-wait, with the next data request generated 10 ms or more later;
2098 // nevertheless for power reasons, we don't want to see too many of these.
Andreas Huber2e8ffaf2010-02-18 16:45:13 -08002099
Andy Hung719b46b2015-05-31 22:18:25 -07002100 ALOGV_IF(actualSize == 0 && buffer->size > 0, "callbackwrapper: empty buffer returned");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002101
2102 buffer->size = actualSize;
2103 } break;
2104
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002105 case AudioTrack::EVENT_STREAM_END:
Andy Hung719b46b2015-05-31 22:18:25 -07002106 // currently only occurs for offloaded callbacks
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002107 ALOGV("callbackwrapper: deliver EVENT_STREAM_END");
2108 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2109 me->mCallbackCookie, CB_EVENT_STREAM_END);
2110 break;
2111
2112 case AudioTrack::EVENT_NEW_IAUDIOTRACK :
2113 ALOGV("callbackwrapper: deliver EVENT_TEAR_DOWN");
2114 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2115 me->mCallbackCookie, CB_EVENT_TEAR_DOWN);
2116 break;
2117
Glenn Kasten421743b2015-06-01 08:18:08 -07002118 case AudioTrack::EVENT_UNDERRUN:
Andy Hung719b46b2015-05-31 22:18:25 -07002119 // This occurs when there is no data available, typically
Glenn Kasten421743b2015-06-01 08:18:08 -07002120 // when there is a failure to supply data to the AudioTrack. It can also
2121 // occur in non-offloaded mode when the audio device comes out of standby.
2122 //
Andy Hung719b46b2015-05-31 22:18:25 -07002123 // If an AudioTrack underruns it outputs silence. Since this happens suddenly
2124 // it may sound like an audible pop or glitch.
2125 //
2126 // The underrun event is sent once per track underrun; the condition is reset
2127 // when more data is sent to the AudioTrack.
Glenn Kasten421743b2015-06-01 08:18:08 -07002128 ALOGI("callbackwrapper: EVENT_UNDERRUN (discarded)");
2129 break;
2130
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002131 default:
2132 ALOGE("received unknown event type: %d inside CallbackWrapper !", event);
Andreas Huber51c1e0e2011-04-04 11:43:40 -07002133 }
2134
Marco Nelissen6b74d672012-02-28 16:07:44 -08002135 data->unlock();
Andreas Huber20111aa2009-07-14 16:56:47 -07002136}
2137
Glenn Kastend848eb42016-03-08 13:42:11 -08002138audio_session_t MediaPlayerService::AudioOutput::getSessionId() const
Eric Laurent8c563ed2010-10-07 18:23:03 -07002139{
Andy Hungd1c74342015-07-07 16:54:23 -07002140 Mutex::Autolock lock(mLock);
Eric Laurent8c563ed2010-10-07 18:23:03 -07002141 return mSessionId;
2142}
2143
Eric Laurent6f59db12013-07-26 17:16:50 -07002144uint32_t MediaPlayerService::AudioOutput::getSampleRate() const
2145{
Andy Hungd1c74342015-07-07 16:54:23 -07002146 Mutex::Autolock lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -07002147 if (mTrack == 0) return 0;
2148 return mTrack->getSampleRate();
2149}
2150
Andy Hungf2c87b32016-04-07 19:49:29 -07002151int64_t MediaPlayerService::AudioOutput::getBufferDurationInUs() const
2152{
2153 Mutex::Autolock lock(mLock);
2154 if (mTrack == 0) {
2155 return 0;
2156 }
2157 int64_t duration;
2158 if (mTrack->getBufferDurationInUs(&duration) != OK) {
2159 return 0;
2160 }
2161 return duration;
2162}
2163
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002164////////////////////////////////////////////////////////////////////////////////
2165
2166struct CallbackThread : public Thread {
2167 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
2168 MediaPlayerBase::AudioSink::AudioCallback cb,
2169 void *cookie);
2170
2171protected:
2172 virtual ~CallbackThread();
2173
2174 virtual bool threadLoop();
2175
2176private:
2177 wp<MediaPlayerBase::AudioSink> mSink;
2178 MediaPlayerBase::AudioSink::AudioCallback mCallback;
2179 void *mCookie;
2180 void *mBuffer;
2181 size_t mBufferSize;
2182
2183 CallbackThread(const CallbackThread &);
2184 CallbackThread &operator=(const CallbackThread &);
2185};
2186
2187CallbackThread::CallbackThread(
2188 const wp<MediaPlayerBase::AudioSink> &sink,
2189 MediaPlayerBase::AudioSink::AudioCallback cb,
2190 void *cookie)
2191 : mSink(sink),
2192 mCallback(cb),
2193 mCookie(cookie),
2194 mBuffer(NULL),
2195 mBufferSize(0) {
2196}
2197
2198CallbackThread::~CallbackThread() {
2199 if (mBuffer) {
2200 free(mBuffer);
2201 mBuffer = NULL;
2202 }
2203}
2204
2205bool CallbackThread::threadLoop() {
2206 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
2207 if (sink == NULL) {
2208 return false;
2209 }
2210
2211 if (mBuffer == NULL) {
2212 mBufferSize = sink->bufferSize();
2213 mBuffer = malloc(mBufferSize);
2214 }
2215
2216 size_t actualSize =
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002217 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie,
2218 MediaPlayerBase::AudioSink::CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002219
2220 if (actualSize > 0) {
2221 sink->write(mBuffer, actualSize);
Andy Hunga31335a2014-08-20 17:37:59 -07002222 // Could return false on sink->write() error or short count.
2223 // Not necessarily appropriate but would work for AudioCache behavior.
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002224 }
2225
2226 return true;
2227}
2228
2229////////////////////////////////////////////////////////////////////////////////
2230
Gloria Wang7cf180c2011-02-19 18:37:57 -08002231void MediaPlayerService::addBatteryData(uint32_t params)
2232{
2233 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002234
2235 int32_t time = systemTime() / 1000000L;
2236
2237 // change audio output devices. This notification comes from AudioFlinger
2238 if ((params & kBatteryDataSpeakerOn)
2239 || (params & kBatteryDataOtherAudioDeviceOn)) {
2240
2241 int deviceOn[NUM_AUDIO_DEVICES];
2242 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2243 deviceOn[i] = 0;
2244 }
2245
2246 if ((params & kBatteryDataSpeakerOn)
2247 && (params & kBatteryDataOtherAudioDeviceOn)) {
2248 deviceOn[SPEAKER_AND_OTHER] = 1;
2249 } else if (params & kBatteryDataSpeakerOn) {
2250 deviceOn[SPEAKER] = 1;
2251 } else {
2252 deviceOn[OTHER_AUDIO_DEVICE] = 1;
2253 }
2254
2255 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2256 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
2257
2258 if (mBatteryAudio.refCount > 0) { // if playing audio
2259 if (!deviceOn[i]) {
2260 mBatteryAudio.lastTime[i] += time;
2261 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2262 mBatteryAudio.lastTime[i] = 0;
2263 } else {
2264 mBatteryAudio.lastTime[i] = 0 - time;
2265 }
2266 }
2267
2268 mBatteryAudio.deviceOn[i] = deviceOn[i];
2269 }
2270 }
2271 return;
2272 }
2273
Marco Nelissenb7848f12014-12-04 08:57:56 -08002274 // an audio stream is started
Gloria Wang9ee159b2011-02-24 14:51:45 -08002275 if (params & kBatteryDataAudioFlingerStart) {
2276 // record the start time only if currently no other audio
2277 // is being played
2278 if (mBatteryAudio.refCount == 0) {
2279 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2280 if (mBatteryAudio.deviceOn[i]) {
2281 mBatteryAudio.lastTime[i] -= time;
2282 }
2283 }
2284 }
2285
2286 mBatteryAudio.refCount ++;
2287 return;
2288
2289 } else if (params & kBatteryDataAudioFlingerStop) {
2290 if (mBatteryAudio.refCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002291 ALOGW("Battery track warning: refCount is <= 0");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002292 return;
2293 }
2294
2295 // record the stop time only if currently this is the only
2296 // audio being played
2297 if (mBatteryAudio.refCount == 1) {
2298 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2299 if (mBatteryAudio.deviceOn[i]) {
2300 mBatteryAudio.lastTime[i] += time;
2301 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2302 mBatteryAudio.lastTime[i] = 0;
2303 }
2304 }
2305 }
2306
2307 mBatteryAudio.refCount --;
2308 return;
2309 }
2310
Gloria Wang7cf180c2011-02-19 18:37:57 -08002311 int uid = IPCThreadState::self()->getCallingUid();
2312 if (uid == AID_MEDIA) {
2313 return;
2314 }
2315 int index = mBatteryData.indexOfKey(uid);
Gloria Wang7cf180c2011-02-19 18:37:57 -08002316
2317 if (index < 0) { // create a new entry for this UID
2318 BatteryUsageInfo info;
2319 info.audioTotalTime = 0;
2320 info.videoTotalTime = 0;
2321 info.audioLastTime = 0;
2322 info.videoLastTime = 0;
2323 info.refCount = 0;
2324
Gloria Wang9ee159b2011-02-24 14:51:45 -08002325 if (mBatteryData.add(uid, info) == NO_MEMORY) {
Steve Block29357bc2012-01-06 19:20:56 +00002326 ALOGE("Battery track error: no memory for new app");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002327 return;
2328 }
Gloria Wang7cf180c2011-02-19 18:37:57 -08002329 }
2330
2331 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
2332
2333 if (params & kBatteryDataCodecStarted) {
2334 if (params & kBatteryDataTrackAudio) {
2335 info.audioLastTime -= time;
2336 info.refCount ++;
2337 }
2338 if (params & kBatteryDataTrackVideo) {
2339 info.videoLastTime -= time;
2340 info.refCount ++;
2341 }
2342 } else {
2343 if (info.refCount == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002344 ALOGW("Battery track warning: refCount is already 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002345 return;
2346 } else if (info.refCount < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00002347 ALOGE("Battery track error: refCount < 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002348 mBatteryData.removeItem(uid);
2349 return;
2350 }
2351
2352 if (params & kBatteryDataTrackAudio) {
2353 info.audioLastTime += time;
2354 info.refCount --;
2355 }
2356 if (params & kBatteryDataTrackVideo) {
2357 info.videoLastTime += time;
2358 info.refCount --;
2359 }
2360
2361 // no stream is being played by this UID
2362 if (info.refCount == 0) {
2363 info.audioTotalTime += info.audioLastTime;
2364 info.audioLastTime = 0;
2365 info.videoTotalTime += info.videoLastTime;
2366 info.videoLastTime = 0;
2367 }
2368 }
2369}
2370
2371status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
2372 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002373
2374 // audio output devices usage
2375 int32_t time = systemTime() / 1000000L; //in ms
2376 int32_t totalTime;
2377
2378 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2379 totalTime = mBatteryAudio.totalTime[i];
2380
2381 if (mBatteryAudio.deviceOn[i]
2382 && (mBatteryAudio.lastTime[i] != 0)) {
2383 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
2384 totalTime += tmpTime;
2385 }
2386
2387 reply->writeInt32(totalTime);
2388 // reset the total time
2389 mBatteryAudio.totalTime[i] = 0;
2390 }
2391
2392 // codec usage
Gloria Wang7cf180c2011-02-19 18:37:57 -08002393 BatteryUsageInfo info;
2394 int size = mBatteryData.size();
2395
2396 reply->writeInt32(size);
2397 int i = 0;
2398
2399 while (i < size) {
2400 info = mBatteryData.valueAt(i);
2401
2402 reply->writeInt32(mBatteryData.keyAt(i)); //UID
2403 reply->writeInt32(info.audioTotalTime);
2404 reply->writeInt32(info.videoTotalTime);
2405
2406 info.audioTotalTime = 0;
2407 info.videoTotalTime = 0;
2408
2409 // remove the UID entry where no stream is being played
2410 if (info.refCount <= 0) {
2411 mBatteryData.removeItemsAt(i);
2412 size --;
2413 i --;
2414 }
2415 i++;
2416 }
2417 return NO_ERROR;
2418}
nikoa64c8c72009-07-20 15:07:26 -07002419} // namespace android