blob: 0f983cdc80db6ea546d698dcde631e86003f7c30 [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
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700653MediaPlayerService::Client::ServiceDeathNotifier::ServiceDeathNotifier(
654 const sp<IBinder>& service,
655 const sp<MediaPlayerBase>& listener,
656 int which) {
657 mService = service;
658 mListener = listener;
659 mWhich = which;
660}
661
662MediaPlayerService::Client::ServiceDeathNotifier::~ServiceDeathNotifier() {
663 mService->unlinkToDeath(this);
664}
665
666void MediaPlayerService::Client::ServiceDeathNotifier::binderDied(const wp<IBinder>& /*who*/) {
667 sp<MediaPlayerBase> listener = mListener.promote();
668 if (listener != NULL) {
669 listener->sendEvent(MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED, mWhich);
670 } else {
671 ALOGW("listener for process %d death is gone", mWhich);
672 }
673}
674
John Grossmanc795b642012-02-22 15:38:35 -0800675sp<MediaPlayerBase> MediaPlayerService::Client::setDataSource_pre(
676 player_type playerType)
677{
678 ALOGV("player type = %d", playerType);
679
680 // create the right type of player
681 sp<MediaPlayerBase> p = createPlayer(playerType);
682 if (p == NULL) {
683 return p;
684 }
685
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700686 sp<IServiceManager> sm = defaultServiceManager();
687 sp<IBinder> binder = sm->getService(String16("media.extractor"));
688 mExtractorDeathListener = new ServiceDeathNotifier(binder, p, MEDIAEXTRACTOR_PROCESS_DEATH);
689 binder->linkToDeath(mExtractorDeathListener);
690
691 binder = sm->getService(String16("media.codec"));
692 mCodecDeathListener = new ServiceDeathNotifier(binder, p, MEDIACODEC_PROCESS_DEATH);
693 binder->linkToDeath(mCodecDeathListener);
694
695 binder = sm->getService(String16("media.audio_flinger"));
696 mAudioDeathListener = new ServiceDeathNotifier(binder, p, AUDIO_PROCESS_DEATH);
697 binder->linkToDeath(mAudioDeathListener);
698
John Grossmanc795b642012-02-22 15:38:35 -0800699 if (!p->hardwareOutput()) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -0700700 Mutex::Autolock l(mLock);
Marco Nelissend457c972014-02-11 08:47:07 -0800701 mAudioOutput = new AudioOutput(mAudioSessionId, IPCThreadState::self()->getCallingUid(),
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700702 mPid, mAudioAttributes);
John Grossmanc795b642012-02-22 15:38:35 -0800703 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
704 }
705
706 return p;
707}
708
709void MediaPlayerService::Client::setDataSource_post(
710 const sp<MediaPlayerBase>& p,
711 status_t status)
712{
713 ALOGV(" setDataSource");
714 mStatus = status;
715 if (mStatus != OK) {
716 ALOGE(" error: %d", mStatus);
717 return;
718 }
719
720 // Set the re-transmission endpoint if one was chosen.
721 if (mRetransmitEndpointValid) {
722 mStatus = p->setRetransmitEndpoint(&mRetransmitEndpoint);
723 if (mStatus != NO_ERROR) {
724 ALOGE("setRetransmitEndpoint error: %d", mStatus);
725 }
726 }
727
728 if (mStatus == OK) {
729 mPlayer = p;
730 }
731}
732
Andreas Huber2db84552010-01-28 11:19:57 -0800733status_t MediaPlayerService::Client::setDataSource(
Andreas Huber1b86fe02014-01-29 11:13:26 -0800734 const sp<IMediaHTTPService> &httpService,
735 const char *url,
736 const KeyedVector<String8, String8> *headers)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800737{
Steve Block3856b092011-10-20 11:56:00 +0100738 ALOGV("setDataSource(%s)", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800739 if (url == NULL)
740 return UNKNOWN_ERROR;
741
Dave Burked681bbb2011-08-30 14:39:17 +0100742 if ((strncmp(url, "http://", 7) == 0) ||
743 (strncmp(url, "https://", 8) == 0) ||
744 (strncmp(url, "rtsp://", 7) == 0)) {
745 if (!checkPermission("android.permission.INTERNET")) {
746 return PERMISSION_DENIED;
747 }
748 }
749
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800750 if (strncmp(url, "content://", 10) == 0) {
751 // get a filedescriptor for the content Uri and
752 // pass it to the setDataSource(fd) method
753
754 String16 url16(url);
755 int fd = android::openContentProviderFile(url16);
756 if (fd < 0)
757 {
Steve Block29357bc2012-01-06 19:20:56 +0000758 ALOGE("Couldn't open fd for %s", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800759 return UNKNOWN_ERROR;
760 }
761 setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
762 close(fd);
763 return mStatus;
764 } else {
John Grossman44a7e422012-06-21 17:29:24 -0700765 player_type playerType = MediaPlayerFactory::getPlayerType(this, url);
John Grossmanc795b642012-02-22 15:38:35 -0800766 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
767 if (p == NULL) {
768 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800769 }
770
Andreas Huber1b86fe02014-01-29 11:13:26 -0800771 setDataSource_post(p, p->setDataSource(httpService, url, headers));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800772 return mStatus;
773 }
774}
775
776status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
777{
Marco Nelissen83b0fd92015-09-16 13:48:07 -0700778 ALOGV("setDataSource fd=%d (%s), offset=%lld, length=%lld",
779 fd, nameForFd(fd).c_str(), (long long) offset, (long long) length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800780 struct stat sb;
781 int ret = fstat(fd, &sb);
782 if (ret != 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000783 ALOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800784 return UNKNOWN_ERROR;
785 }
786
Andy Hung833b4752016-04-04 17:15:48 -0700787 ALOGV("st_dev = %llu", static_cast<unsigned long long>(sb.st_dev));
Steve Block3856b092011-10-20 11:56:00 +0100788 ALOGV("st_mode = %u", sb.st_mode);
Mark Salyzyn77342f72014-06-18 16:31:32 -0700789 ALOGV("st_uid = %lu", static_cast<unsigned long>(sb.st_uid));
790 ALOGV("st_gid = %lu", static_cast<unsigned long>(sb.st_gid));
Andy Hung833b4752016-04-04 17:15:48 -0700791 ALOGV("st_size = %llu", static_cast<unsigned long long>(sb.st_size));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800792
793 if (offset >= sb.st_size) {
Steve Block29357bc2012-01-06 19:20:56 +0000794 ALOGE("offset error");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800795 return UNKNOWN_ERROR;
796 }
797 if (offset + length > sb.st_size) {
798 length = sb.st_size - offset;
Andy Hung833b4752016-04-04 17:15:48 -0700799 ALOGV("calculated length = %lld", (long long)length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800800 }
801
John Grossman44a7e422012-06-21 17:29:24 -0700802 player_type playerType = MediaPlayerFactory::getPlayerType(this,
803 fd,
804 offset,
805 length);
John Grossmanc795b642012-02-22 15:38:35 -0800806 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
807 if (p == NULL) {
808 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800809 }
810
811 // now set data source
John Grossmanc795b642012-02-22 15:38:35 -0800812 setDataSource_post(p, p->setDataSource(fd, offset, length));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800813 return mStatus;
814}
815
Andreas Hubere2b10282010-11-23 11:41:34 -0800816status_t MediaPlayerService::Client::setDataSource(
817 const sp<IStreamSource> &source) {
818 // create the right type of player
John Grossman44a7e422012-06-21 17:29:24 -0700819 player_type playerType = MediaPlayerFactory::getPlayerType(this, source);
John Grossmanc795b642012-02-22 15:38:35 -0800820 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
Andreas Hubere2b10282010-11-23 11:41:34 -0800821 if (p == NULL) {
822 return NO_INIT;
823 }
824
Andreas Hubere2b10282010-11-23 11:41:34 -0800825 // now set data source
John Grossmanc795b642012-02-22 15:38:35 -0800826 setDataSource_post(p, p->setDataSource(source));
Andreas Hubere2b10282010-11-23 11:41:34 -0800827 return mStatus;
828}
829
Chris Watkins99f31602015-03-20 13:06:33 -0700830status_t MediaPlayerService::Client::setDataSource(
831 const sp<IDataSource> &source) {
832 sp<DataSource> dataSource = DataSource::CreateFromIDataSource(source);
833 player_type playerType = MediaPlayerFactory::getPlayerType(this, dataSource);
834 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
835 if (p == NULL) {
836 return NO_INIT;
837 }
838 // now set data source
839 setDataSource_post(p, p->setDataSource(dataSource));
840 return mStatus;
841}
842
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700843void MediaPlayerService::Client::disconnectNativeWindow() {
844 if (mConnectedWindow != NULL) {
845 status_t err = native_window_api_disconnect(mConnectedWindow.get(),
846 NATIVE_WINDOW_API_MEDIA);
847
848 if (err != OK) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000849 ALOGW("native_window_api_disconnect returned an error: %s (%d)",
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700850 strerror(-err), err);
851 }
852 }
853 mConnectedWindow.clear();
854}
855
Glenn Kasten11731182011-02-08 17:26:17 -0800856status_t MediaPlayerService::Client::setVideoSurfaceTexture(
Andy McFadden484566c2012-12-18 09:46:54 -0800857 const sp<IGraphicBufferProducer>& bufferProducer)
Glenn Kasten11731182011-02-08 17:26:17 -0800858{
Andy McFadden484566c2012-12-18 09:46:54 -0800859 ALOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, bufferProducer.get());
Glenn Kasten11731182011-02-08 17:26:17 -0800860 sp<MediaPlayerBase> p = getPlayer();
861 if (p == 0) return UNKNOWN_ERROR;
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700862
Marco Nelissenf8880202014-11-14 07:58:25 -0800863 sp<IBinder> binder(IInterface::asBinder(bufferProducer));
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700864 if (mConnectedWindowBinder == binder) {
865 return OK;
866 }
867
868 sp<ANativeWindow> anw;
Andy McFadden484566c2012-12-18 09:46:54 -0800869 if (bufferProducer != NULL) {
Marco Nelissenee08f7e2013-09-16 13:30:01 -0700870 anw = new Surface(bufferProducer, true /* controlledByApp */);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700871 status_t err = native_window_api_connect(anw.get(),
872 NATIVE_WINDOW_API_MEDIA);
873
874 if (err != OK) {
Steve Block29357bc2012-01-06 19:20:56 +0000875 ALOGE("setVideoSurfaceTexture failed: %d", err);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700876 // Note that we must do the reset before disconnecting from the ANW.
877 // Otherwise queue/dequeue calls could be made on the disconnected
878 // ANW, which may result in errors.
879 reset();
880
881 disconnectNativeWindow();
882
883 return err;
884 }
885 }
886
Andy McFadden484566c2012-12-18 09:46:54 -0800887 // Note that we must set the player's new GraphicBufferProducer before
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700888 // disconnecting the old one. Otherwise queue/dequeue calls could be made
889 // on the disconnected ANW, which may result in errors.
Andy McFadden484566c2012-12-18 09:46:54 -0800890 status_t err = p->setVideoSurfaceTexture(bufferProducer);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700891
892 disconnectNativeWindow();
893
894 mConnectedWindow = anw;
895
896 if (err == OK) {
897 mConnectedWindowBinder = binder;
898 } else {
899 disconnectNativeWindow();
900 }
901
902 return err;
Glenn Kasten11731182011-02-08 17:26:17 -0800903}
904
Nicolas Catania1d187f12009-05-12 23:25:55 -0700905status_t MediaPlayerService::Client::invoke(const Parcel& request,
906 Parcel *reply)
907{
908 sp<MediaPlayerBase> p = getPlayer();
909 if (p == NULL) return UNKNOWN_ERROR;
910 return p->invoke(request, reply);
911}
912
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700913// This call doesn't need to access the native player.
914status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
915{
916 status_t status;
nikoa64c8c72009-07-20 15:07:26 -0700917 media::Metadata::Filter allow, drop;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700918
Nicolas Catania48290382009-07-10 13:53:06 -0700919 if (unmarshallFilter(filter, &allow, &status) &&
920 unmarshallFilter(filter, &drop, &status)) {
921 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700922
923 mMetadataAllow = allow;
924 mMetadataDrop = drop;
925 }
926 return status;
927}
928
Nicolas Catania48290382009-07-10 13:53:06 -0700929status_t MediaPlayerService::Client::getMetadata(
Mark Salyzyn77342f72014-06-18 16:31:32 -0700930 bool update_only, bool /*apply_filter*/, Parcel *reply)
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700931{
nikoa64c8c72009-07-20 15:07:26 -0700932 sp<MediaPlayerBase> player = getPlayer();
933 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania48290382009-07-10 13:53:06 -0700934
nikod608a812009-07-16 16:39:53 -0700935 status_t status;
936 // Placeholder for the return code, updated by the caller.
937 reply->writeInt32(-1);
938
nikoa64c8c72009-07-20 15:07:26 -0700939 media::Metadata::Filter ids;
Nicolas Catania48290382009-07-10 13:53:06 -0700940
941 // We don't block notifications while we fetch the data. We clear
942 // mMetadataUpdated first so we don't lose notifications happening
943 // during the rest of this call.
944 {
945 Mutex::Autolock lock(mLock);
946 if (update_only) {
nikod608a812009-07-16 16:39:53 -0700947 ids = mMetadataUpdated;
Nicolas Catania48290382009-07-10 13:53:06 -0700948 }
949 mMetadataUpdated.clear();
950 }
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700951
nikoa64c8c72009-07-20 15:07:26 -0700952 media::Metadata metadata(reply);
Nicolas Catania48290382009-07-10 13:53:06 -0700953
nikoa64c8c72009-07-20 15:07:26 -0700954 metadata.appendHeader();
955 status = player->getMetadata(ids, reply);
nikod608a812009-07-16 16:39:53 -0700956
957 if (status != OK) {
nikoa64c8c72009-07-20 15:07:26 -0700958 metadata.resetParcel();
Steve Block29357bc2012-01-06 19:20:56 +0000959 ALOGE("getMetadata failed %d", status);
nikod608a812009-07-16 16:39:53 -0700960 return status;
961 }
962
963 // FIXME: Implement filtering on the result. Not critical since
964 // filtering takes place on the update notifications already. This
965 // would be when all the metadata are fetch and a filter is set.
966
nikod608a812009-07-16 16:39:53 -0700967 // Everything is fine, update the metadata length.
nikoa64c8c72009-07-20 15:07:26 -0700968 metadata.updateLength();
nikod608a812009-07-16 16:39:53 -0700969 return OK;
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700970}
971
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800972status_t MediaPlayerService::Client::prepareAsync()
973{
Steve Block3856b092011-10-20 11:56:00 +0100974 ALOGV("[%d] prepareAsync", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800975 sp<MediaPlayerBase> p = getPlayer();
976 if (p == 0) return UNKNOWN_ERROR;
977 status_t ret = p->prepareAsync();
978#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000979 ALOGD("start Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800980 if (ret == NO_ERROR) mAntagonizer->start();
981#endif
982 return ret;
983}
984
985status_t MediaPlayerService::Client::start()
986{
Steve Block3856b092011-10-20 11:56:00 +0100987 ALOGV("[%d] start", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800988 sp<MediaPlayerBase> p = getPlayer();
989 if (p == 0) return UNKNOWN_ERROR;
990 p->setLooping(mLoop);
991 return p->start();
992}
993
994status_t MediaPlayerService::Client::stop()
995{
Steve Block3856b092011-10-20 11:56:00 +0100996 ALOGV("[%d] stop", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800997 sp<MediaPlayerBase> p = getPlayer();
998 if (p == 0) return UNKNOWN_ERROR;
999 return p->stop();
1000}
1001
1002status_t MediaPlayerService::Client::pause()
1003{
Steve Block3856b092011-10-20 11:56:00 +01001004 ALOGV("[%d] pause", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001005 sp<MediaPlayerBase> p = getPlayer();
1006 if (p == 0) return UNKNOWN_ERROR;
1007 return p->pause();
1008}
1009
1010status_t MediaPlayerService::Client::isPlaying(bool* state)
1011{
1012 *state = false;
1013 sp<MediaPlayerBase> p = getPlayer();
1014 if (p == 0) return UNKNOWN_ERROR;
1015 *state = p->isPlaying();
Steve Block3856b092011-10-20 11:56:00 +01001016 ALOGV("[%d] isPlaying: %d", mConnId, *state);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001017 return NO_ERROR;
1018}
1019
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001020status_t MediaPlayerService::Client::setPlaybackSettings(const AudioPlaybackRate& rate)
Wei Jia98160162015-02-04 17:01:11 -08001021{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001022 ALOGV("[%d] setPlaybackSettings(%f, %f, %d, %d)",
1023 mConnId, rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Wei Jia98160162015-02-04 17:01:11 -08001024 sp<MediaPlayerBase> p = getPlayer();
1025 if (p == 0) return UNKNOWN_ERROR;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001026 return p->setPlaybackSettings(rate);
1027}
1028
1029status_t MediaPlayerService::Client::getPlaybackSettings(AudioPlaybackRate* rate /* nonnull */)
1030{
1031 sp<MediaPlayerBase> p = getPlayer();
1032 if (p == 0) return UNKNOWN_ERROR;
1033 status_t ret = p->getPlaybackSettings(rate);
1034 if (ret == NO_ERROR) {
1035 ALOGV("[%d] getPlaybackSettings(%f, %f, %d, %d)",
1036 mConnId, rate->mSpeed, rate->mPitch, rate->mFallbackMode, rate->mStretchMode);
1037 } else {
1038 ALOGV("[%d] getPlaybackSettings returned %d", mConnId, ret);
1039 }
1040 return ret;
1041}
1042
1043status_t MediaPlayerService::Client::setSyncSettings(
1044 const AVSyncSettings& sync, float videoFpsHint)
1045{
1046 ALOGV("[%d] setSyncSettings(%u, %u, %f, %f)",
1047 mConnId, sync.mSource, sync.mAudioAdjustMode, sync.mTolerance, videoFpsHint);
1048 sp<MediaPlayerBase> p = getPlayer();
1049 if (p == 0) return UNKNOWN_ERROR;
1050 return p->setSyncSettings(sync, videoFpsHint);
1051}
1052
1053status_t MediaPlayerService::Client::getSyncSettings(
1054 AVSyncSettings* sync /* nonnull */, float* videoFps /* nonnull */)
1055{
1056 sp<MediaPlayerBase> p = getPlayer();
1057 if (p == 0) return UNKNOWN_ERROR;
1058 status_t ret = p->getSyncSettings(sync, videoFps);
1059 if (ret == NO_ERROR) {
1060 ALOGV("[%d] getSyncSettings(%u, %u, %f, %f)",
1061 mConnId, sync->mSource, sync->mAudioAdjustMode, sync->mTolerance, *videoFps);
1062 } else {
1063 ALOGV("[%d] getSyncSettings returned %d", mConnId, ret);
1064 }
1065 return ret;
Wei Jia98160162015-02-04 17:01:11 -08001066}
1067
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001068status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
1069{
Steve Block3856b092011-10-20 11:56:00 +01001070 ALOGV("getCurrentPosition");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001071 sp<MediaPlayerBase> p = getPlayer();
1072 if (p == 0) return UNKNOWN_ERROR;
1073 status_t ret = p->getCurrentPosition(msec);
1074 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001075 ALOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001076 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001077 ALOGE("getCurrentPosition returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001078 }
1079 return ret;
1080}
1081
1082status_t MediaPlayerService::Client::getDuration(int *msec)
1083{
Steve Block3856b092011-10-20 11:56:00 +01001084 ALOGV("getDuration");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001085 sp<MediaPlayerBase> p = getPlayer();
1086 if (p == 0) return UNKNOWN_ERROR;
1087 status_t ret = p->getDuration(msec);
1088 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001089 ALOGV("[%d] getDuration = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001090 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001091 ALOGE("getDuration returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001092 }
1093 return ret;
1094}
1095
Marco Nelissen6b74d672012-02-28 16:07:44 -08001096status_t MediaPlayerService::Client::setNextPlayer(const sp<IMediaPlayer>& player) {
1097 ALOGV("setNextPlayer");
1098 Mutex::Autolock l(mLock);
1099 sp<Client> c = static_cast<Client*>(player.get());
1100 mNextClient = c;
John Grossman5f7e55e2012-08-24 14:47:25 -07001101
1102 if (c != NULL) {
1103 if (mAudioOutput != NULL) {
1104 mAudioOutput->setNextOutput(c->mAudioOutput);
1105 } else if ((mPlayer != NULL) && !mPlayer->hardwareOutput()) {
1106 ALOGE("no current audio output");
1107 }
1108
1109 if ((mPlayer != NULL) && (mNextClient->getPlayer() != NULL)) {
1110 mPlayer->setNextPlayer(mNextClient->getPlayer());
1111 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001112 }
John Grossman5f7e55e2012-08-24 14:47:25 -07001113
Marco Nelissen6b74d672012-02-28 16:07:44 -08001114 return OK;
1115}
1116
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001117status_t MediaPlayerService::Client::seekTo(int msec)
1118{
Steve Block3856b092011-10-20 11:56:00 +01001119 ALOGV("[%d] seekTo(%d)", mConnId, msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001120 sp<MediaPlayerBase> p = getPlayer();
1121 if (p == 0) return UNKNOWN_ERROR;
1122 return p->seekTo(msec);
1123}
1124
1125status_t MediaPlayerService::Client::reset()
1126{
Steve Block3856b092011-10-20 11:56:00 +01001127 ALOGV("[%d] reset", mConnId);
John Grossmanc795b642012-02-22 15:38:35 -08001128 mRetransmitEndpointValid = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001129 sp<MediaPlayerBase> p = getPlayer();
1130 if (p == 0) return UNKNOWN_ERROR;
1131 return p->reset();
1132}
1133
Glenn Kastenfff6d712012-01-12 16:38:12 -08001134status_t MediaPlayerService::Client::setAudioStreamType(audio_stream_type_t type)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001135{
Steve Block3856b092011-10-20 11:56:00 +01001136 ALOGV("[%d] setAudioStreamType(%d)", mConnId, type);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001137 // TODO: for hardware output, call player instead
1138 Mutex::Autolock l(mLock);
1139 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1140 return NO_ERROR;
1141}
1142
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001143status_t MediaPlayerService::Client::setAudioAttributes_l(const Parcel &parcel)
1144{
1145 if (mAudioAttributes != NULL) { free(mAudioAttributes); }
1146 mAudioAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001147 if (mAudioAttributes == NULL) {
1148 return NO_MEMORY;
1149 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001150 unmarshallAudioAttributes(parcel, mAudioAttributes);
1151
1152 ALOGV("setAudioAttributes_l() usage=%d content=%d flags=0x%x tags=%s",
1153 mAudioAttributes->usage, mAudioAttributes->content_type, mAudioAttributes->flags,
1154 mAudioAttributes->tags);
1155
1156 if (mAudioOutput != 0) {
1157 mAudioOutput->setAudioAttributes(mAudioAttributes);
1158 }
1159 return NO_ERROR;
1160}
1161
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001162status_t MediaPlayerService::Client::setLooping(int loop)
1163{
Steve Block3856b092011-10-20 11:56:00 +01001164 ALOGV("[%d] setLooping(%d)", mConnId, loop);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001165 mLoop = loop;
1166 sp<MediaPlayerBase> p = getPlayer();
1167 if (p != 0) return p->setLooping(loop);
1168 return NO_ERROR;
1169}
1170
1171status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1172{
Steve Block3856b092011-10-20 11:56:00 +01001173 ALOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
John Grossman761defc2012-02-09 15:09:05 -08001174
1175 // for hardware output, call player instead
1176 sp<MediaPlayerBase> p = getPlayer();
1177 {
1178 Mutex::Autolock l(mLock);
1179 if (p != 0 && p->hardwareOutput()) {
1180 MediaPlayerHWInterface* hwp =
1181 reinterpret_cast<MediaPlayerHWInterface*>(p.get());
1182 return hwp->setVolume(leftVolume, rightVolume);
1183 } else {
1184 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1185 return NO_ERROR;
1186 }
1187 }
1188
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001189 return NO_ERROR;
1190}
1191
Eric Laurent2beeb502010-07-16 07:43:46 -07001192status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1193{
Steve Block3856b092011-10-20 11:56:00 +01001194 ALOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
Eric Laurent2beeb502010-07-16 07:43:46 -07001195 Mutex::Autolock l(mLock);
1196 if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1197 return NO_ERROR;
1198}
1199
1200status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1201{
Steve Block3856b092011-10-20 11:56:00 +01001202 ALOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
Eric Laurent2beeb502010-07-16 07:43:46 -07001203 Mutex::Autolock l(mLock);
1204 if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1205 return NO_ERROR;
1206}
Nicolas Catania48290382009-07-10 13:53:06 -07001207
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001208status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
Steve Block3856b092011-10-20 11:56:00 +01001209 ALOGV("[%d] setParameter(%d)", mConnId, key);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001210 switch (key) {
1211 case KEY_PARAMETER_AUDIO_ATTRIBUTES:
1212 {
1213 Mutex::Autolock l(mLock);
1214 return setAudioAttributes_l(request);
1215 }
1216 default:
1217 sp<MediaPlayerBase> p = getPlayer();
1218 if (p == 0) { return UNKNOWN_ERROR; }
1219 return p->setParameter(key, request);
1220 }
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001221}
1222
1223status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
Steve Block3856b092011-10-20 11:56:00 +01001224 ALOGV("[%d] getParameter(%d)", mConnId, key);
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001225 sp<MediaPlayerBase> p = getPlayer();
1226 if (p == 0) return UNKNOWN_ERROR;
1227 return p->getParameter(key, reply);
1228}
1229
John Grossmanc795b642012-02-22 15:38:35 -08001230status_t MediaPlayerService::Client::setRetransmitEndpoint(
1231 const struct sockaddr_in* endpoint) {
1232
1233 if (NULL != endpoint) {
1234 uint32_t a = ntohl(endpoint->sin_addr.s_addr);
1235 uint16_t p = ntohs(endpoint->sin_port);
1236 ALOGV("[%d] setRetransmitEndpoint(%u.%u.%u.%u:%hu)", mConnId,
1237 (a >> 24), (a >> 16) & 0xFF, (a >> 8) & 0xFF, (a & 0xFF), p);
1238 } else {
1239 ALOGV("[%d] setRetransmitEndpoint = <none>", mConnId);
1240 }
1241
1242 sp<MediaPlayerBase> p = getPlayer();
1243
1244 // Right now, the only valid time to set a retransmit endpoint is before
1245 // player selection has been made (since the presence or absence of a
1246 // retransmit endpoint is going to determine which player is selected during
1247 // setDataSource).
1248 if (p != 0) return INVALID_OPERATION;
1249
1250 if (NULL != endpoint) {
1251 mRetransmitEndpoint = *endpoint;
1252 mRetransmitEndpointValid = true;
1253 } else {
1254 mRetransmitEndpointValid = false;
1255 }
1256
1257 return NO_ERROR;
1258}
1259
John Grossman44a7e422012-06-21 17:29:24 -07001260status_t MediaPlayerService::Client::getRetransmitEndpoint(
1261 struct sockaddr_in* endpoint)
1262{
1263 if (NULL == endpoint)
1264 return BAD_VALUE;
1265
1266 sp<MediaPlayerBase> p = getPlayer();
1267
1268 if (p != NULL)
1269 return p->getRetransmitEndpoint(endpoint);
1270
1271 if (!mRetransmitEndpointValid)
1272 return NO_INIT;
1273
1274 *endpoint = mRetransmitEndpoint;
1275
1276 return NO_ERROR;
1277}
1278
Gloria Wangb483c472011-04-11 17:23:27 -07001279void MediaPlayerService::Client::notify(
1280 void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001281{
1282 Client* client = static_cast<Client*>(cookie);
James Dongb8a98252012-08-26 16:13:03 -07001283 if (client == NULL) {
1284 return;
1285 }
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001286
James Dongb8a98252012-08-26 16:13:03 -07001287 sp<IMediaPlayerClient> c;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001288 {
1289 Mutex::Autolock l(client->mLock);
James Dongb8a98252012-08-26 16:13:03 -07001290 c = client->mClient;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001291 if (msg == MEDIA_PLAYBACK_COMPLETE && client->mNextClient != NULL) {
John Grossmancb0b7552012-08-23 17:47:31 -07001292 if (client->mAudioOutput != NULL)
1293 client->mAudioOutput->switchToNextOutput();
Marco Nelissen6b74d672012-02-28 16:07:44 -08001294 client->mNextClient->start();
Wei Jia2afac0c2016-01-07 12:13:07 -08001295 if (client->mNextClient->mClient != NULL) {
1296 client->mNextClient->mClient->notify(
1297 MEDIA_INFO, MEDIA_INFO_STARTED_AS_NEXT, 0, obj);
1298 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001299 }
1300 }
1301
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001302 if (MEDIA_INFO == msg &&
Nicolas Catania48290382009-07-10 13:53:06 -07001303 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikoa64c8c72009-07-20 15:07:26 -07001304 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania48290382009-07-10 13:53:06 -07001305
1306 if(client->shouldDropMetadata(metadata_type)) {
1307 return;
1308 }
1309
1310 // Update the list of metadata that have changed. getMetadata
1311 // also access mMetadataUpdated and clears it.
1312 client->addNewMetadataUpdate(metadata_type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001313 }
James Dongb8a98252012-08-26 16:13:03 -07001314
1315 if (c != NULL) {
1316 ALOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
1317 c->notify(msg, ext1, ext2, obj);
1318 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001319}
1320
Nicolas Catania48290382009-07-10 13:53:06 -07001321
nikoa64c8c72009-07-20 15:07:26 -07001322bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001323{
Nicolas Catania48290382009-07-10 13:53:06 -07001324 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001325
Nicolas Catania48290382009-07-10 13:53:06 -07001326 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001327 return true;
1328 }
1329
Nicolas Catania48290382009-07-10 13:53:06 -07001330 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001331 return false;
Nicolas Catania48290382009-07-10 13:53:06 -07001332 } else {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001333 return true;
1334 }
1335}
1336
Nicolas Catania48290382009-07-10 13:53:06 -07001337
nikoa64c8c72009-07-20 15:07:26 -07001338void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania48290382009-07-10 13:53:06 -07001339 Mutex::Autolock lock(mLock);
1340 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1341 mMetadataUpdated.add(metadata_type);
1342 }
1343}
1344
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001345#if CALLBACK_ANTAGONIZER
1346const int Antagonizer::interval = 10000; // 10 msecs
1347
1348Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1349 mExit(false), mActive(false), mClient(client), mCb(cb)
1350{
1351 createThread(callbackThread, this);
1352}
1353
1354void Antagonizer::kill()
1355{
1356 Mutex::Autolock _l(mLock);
1357 mActive = false;
1358 mExit = true;
1359 mCondition.wait(mLock);
1360}
1361
1362int Antagonizer::callbackThread(void* user)
1363{
Steve Blockb8a80522011-12-20 16:23:08 +00001364 ALOGD("Antagonizer started");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001365 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1366 while (!p->mExit) {
1367 if (p->mActive) {
Steve Block3856b092011-10-20 11:56:00 +01001368 ALOGV("send event");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001369 p->mCb(p->mClient, 0, 0, 0);
1370 }
1371 usleep(interval);
1372 }
1373 Mutex::Autolock _l(p->mLock);
1374 p->mCondition.signal();
Steve Blockb8a80522011-12-20 16:23:08 +00001375 ALOGD("Antagonizer stopped");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001376 return 0;
1377}
1378#endif
1379
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001380#undef LOG_TAG
1381#define LOG_TAG "AudioSink"
Glenn Kastend848eb42016-03-08 13:42:11 -08001382MediaPlayerService::AudioOutput::AudioOutput(audio_session_t sessionId, int uid, int pid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001383 const audio_attributes_t* attr)
Andreas Huber20111aa2009-07-14 16:56:47 -07001384 : mCallback(NULL),
Eric Laurenta514bdb2010-06-21 09:27:30 -07001385 mCallbackCookie(NULL),
Marco Nelissen6b74d672012-02-28 16:07:44 -08001386 mCallbackData(NULL),
Andy Hungd1c74342015-07-07 16:54:23 -07001387 mStreamType(AUDIO_STREAM_MUSIC),
Andy Hungd1c74342015-07-07 16:54:23 -07001388 mLeftVolume(1.0),
1389 mRightVolume(1.0),
1390 mPlaybackRate(AUDIO_PLAYBACK_RATE_DEFAULT),
1391 mSampleRateHz(0),
1392 mMsecsPerFrame(0),
1393 mFrameSize(0),
Eric Laurent1948eb32012-04-13 16:50:19 -07001394 mSessionId(sessionId),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001395 mUid(uid),
Marco Nelissend457c972014-02-11 08:47:07 -08001396 mPid(pid),
Andy Hungd1c74342015-07-07 16:54:23 -07001397 mSendLevel(0.0),
1398 mAuxEffectId(0),
1399 mFlags(AUDIO_OUTPUT_FLAG_NONE)
1400{
Steve Block3856b092011-10-20 11:56:00 +01001401 ALOGV("AudioOutput(%d)", sessionId);
Eric Laurent43562692015-07-15 16:49:07 -07001402 if (attr != NULL) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001403 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1404 if (mAttributes != NULL) {
1405 memcpy(mAttributes, attr, sizeof(audio_attributes_t));
1406 mStreamType = audio_attributes_to_stream_type(attr);
1407 }
1408 } else {
1409 mAttributes = NULL;
Eric Laurent43562692015-07-15 16:49:07 -07001410 }
1411
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001412 setMinBufferCount();
1413}
1414
1415MediaPlayerService::AudioOutput::~AudioOutput()
1416{
1417 close();
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001418 free(mAttributes);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001419 delete mCallbackData;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001420}
1421
Andy Hungd1c74342015-07-07 16:54:23 -07001422//static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001423void MediaPlayerService::AudioOutput::setMinBufferCount()
1424{
1425 char value[PROPERTY_VALUE_MAX];
1426 if (property_get("ro.kernel.qemu", value, 0)) {
1427 mIsOnEmulator = true;
1428 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1429 }
1430}
1431
Andy Hungd1c74342015-07-07 16:54:23 -07001432// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001433bool MediaPlayerService::AudioOutput::isOnEmulator()
1434{
Andy Hungd1c74342015-07-07 16:54:23 -07001435 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001436 return mIsOnEmulator;
1437}
1438
Andy Hungd1c74342015-07-07 16:54:23 -07001439// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001440int MediaPlayerService::AudioOutput::getMinBufferCount()
1441{
Andy Hungd1c74342015-07-07 16:54:23 -07001442 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001443 return mMinBufferCount;
1444}
1445
1446ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1447{
Andy Hungd1c74342015-07-07 16:54:23 -07001448 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001449 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001450 return mTrack->frameCount() * mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001451}
1452
1453ssize_t MediaPlayerService::AudioOutput::frameCount() const
1454{
Andy Hungd1c74342015-07-07 16:54:23 -07001455 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001456 if (mTrack == 0) return NO_INIT;
1457 return mTrack->frameCount();
1458}
1459
1460ssize_t MediaPlayerService::AudioOutput::channelCount() const
1461{
Andy Hungd1c74342015-07-07 16:54:23 -07001462 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001463 if (mTrack == 0) return NO_INIT;
1464 return mTrack->channelCount();
1465}
1466
1467ssize_t MediaPlayerService::AudioOutput::frameSize() const
1468{
Andy Hungd1c74342015-07-07 16:54:23 -07001469 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001470 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001471 return mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001472}
1473
1474uint32_t MediaPlayerService::AudioOutput::latency () const
1475{
Andy Hungd1c74342015-07-07 16:54:23 -07001476 Mutex::Autolock lock(mLock);
Eric Laurentdb354e52012-03-05 17:27:11 -08001477 if (mTrack == 0) return 0;
1478 return mTrack->latency();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001479}
1480
1481float MediaPlayerService::AudioOutput::msecsPerFrame() const
1482{
Andy Hungd1c74342015-07-07 16:54:23 -07001483 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001484 return mMsecsPerFrame;
1485}
1486
Marco Nelissen4110c102012-03-29 09:31:28 -07001487status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position) const
Eric Laurent342e9cf2010-01-19 17:37:09 -08001488{
Andy Hungd1c74342015-07-07 16:54:23 -07001489 Mutex::Autolock lock(mLock);
Eric Laurent342e9cf2010-01-19 17:37:09 -08001490 if (mTrack == 0) return NO_INIT;
1491 return mTrack->getPosition(position);
1492}
1493
Lajos Molnar06ad1522014-08-28 07:27:44 -07001494status_t MediaPlayerService::AudioOutput::getTimestamp(AudioTimestamp &ts) const
1495{
Andy Hungd1c74342015-07-07 16:54:23 -07001496 Mutex::Autolock lock(mLock);
Lajos Molnar06ad1522014-08-28 07:27:44 -07001497 if (mTrack == 0) return NO_INIT;
1498 return mTrack->getTimestamp(ts);
1499}
1500
Wei Jiac4ac8172015-10-21 10:35:48 -07001501// TODO: Remove unnecessary calls to getPlayedOutDurationUs()
1502// as it acquires locks and may query the audio driver.
1503//
1504// Some calls could conceivably retrieve extrapolated data instead of
1505// accessing getTimestamp() or getPosition() every time a data buffer with
1506// a media time is received.
1507//
1508// Calculate duration of played samples if played at normal rate (i.e., 1.0).
1509int64_t MediaPlayerService::AudioOutput::getPlayedOutDurationUs(int64_t nowUs) const
1510{
1511 Mutex::Autolock lock(mLock);
1512 if (mTrack == 0 || mSampleRateHz == 0) {
Wei Jia213f4902015-10-22 08:55:25 -07001513 return 0;
Wei Jiac4ac8172015-10-21 10:35:48 -07001514 }
1515
1516 uint32_t numFramesPlayed;
1517 int64_t numFramesPlayedAt;
1518 AudioTimestamp ts;
1519 static const int64_t kStaleTimestamp100ms = 100000;
1520
1521 status_t res = mTrack->getTimestamp(ts);
1522 if (res == OK) { // case 1: mixing audio tracks and offloaded tracks.
1523 numFramesPlayed = ts.mPosition;
1524 numFramesPlayedAt = ts.mTime.tv_sec * 1000000LL + ts.mTime.tv_nsec / 1000;
1525 const int64_t timestampAge = nowUs - numFramesPlayedAt;
1526 if (timestampAge > kStaleTimestamp100ms) {
1527 // This is an audio FIXME.
1528 // getTimestamp returns a timestamp which may come from audio mixing threads.
1529 // After pausing, the MixerThread may go idle, thus the mTime estimate may
1530 // become stale. Assuming that the MixerThread runs 20ms, with FastMixer at 5ms,
1531 // the max latency should be about 25ms with an average around 12ms (to be verified).
1532 // For safety we use 100ms.
1533 ALOGV("getTimestamp: returned stale timestamp nowUs(%lld) numFramesPlayedAt(%lld)",
1534 (long long)nowUs, (long long)numFramesPlayedAt);
1535 numFramesPlayedAt = nowUs - kStaleTimestamp100ms;
1536 }
1537 //ALOGD("getTimestamp: OK %d %lld", numFramesPlayed, (long long)numFramesPlayedAt);
1538 } else if (res == WOULD_BLOCK) { // case 2: transitory state on start of a new track
1539 numFramesPlayed = 0;
1540 numFramesPlayedAt = nowUs;
1541 //ALOGD("getTimestamp: WOULD_BLOCK %d %lld",
1542 // numFramesPlayed, (long long)numFramesPlayedAt);
1543 } else { // case 3: transitory at new track or audio fast tracks.
1544 res = mTrack->getPosition(&numFramesPlayed);
1545 CHECK_EQ(res, (status_t)OK);
1546 numFramesPlayedAt = nowUs;
1547 numFramesPlayedAt += 1000LL * mTrack->latency() / 2; /* XXX */
1548 //ALOGD("getPosition: %u %lld", numFramesPlayed, (long long)numFramesPlayedAt);
1549 }
1550
1551 // CHECK_EQ(numFramesPlayed & (1 << 31), 0); // can't be negative until 12.4 hrs, test
1552 // TODO: remove the (int32_t) casting below as it may overflow at 12.4 hours.
1553 int64_t durationUs = (int64_t)((int32_t)numFramesPlayed * 1000000LL / mSampleRateHz)
1554 + nowUs - numFramesPlayedAt;
1555 if (durationUs < 0) {
1556 // Occurs when numFramesPlayed position is very small and the following:
1557 // (1) In case 1, the time nowUs is computed before getTimestamp() is called and
1558 // numFramesPlayedAt is greater than nowUs by time more than numFramesPlayed.
1559 // (2) In case 3, using getPosition and adding mAudioSink->latency() to
1560 // numFramesPlayedAt, by a time amount greater than numFramesPlayed.
1561 //
1562 // Both of these are transitory conditions.
1563 ALOGV("getPlayedOutDurationUs: negative duration %lld set to zero", (long long)durationUs);
1564 durationUs = 0;
1565 }
1566 ALOGV("getPlayedOutDurationUs(%lld) nowUs(%lld) frames(%u) framesAt(%lld)",
1567 (long long)durationUs, (long long)nowUs, numFramesPlayed, (long long)numFramesPlayedAt);
1568 return durationUs;
1569}
1570
Marco Nelissen4110c102012-03-29 09:31:28 -07001571status_t MediaPlayerService::AudioOutput::getFramesWritten(uint32_t *frameswritten) const
1572{
Andy Hungd1c74342015-07-07 16:54:23 -07001573 Mutex::Autolock lock(mLock);
Marco Nelissen4110c102012-03-29 09:31:28 -07001574 if (mTrack == 0) return NO_INIT;
Andy Hung2f6e73d2016-04-08 12:12:58 -07001575 ExtendedTimestamp ets;
1576 status_t status = mTrack->getTimestamp(&ets);
1577 if (status == OK || status == WOULD_BLOCK) {
1578 *frameswritten = (uint32_t)ets.mPosition[ExtendedTimestamp::LOCATION_CLIENT];
1579 }
1580 return status;
Marco Nelissen4110c102012-03-29 09:31:28 -07001581}
1582
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001583status_t MediaPlayerService::AudioOutput::setParameters(const String8& keyValuePairs)
1584{
Andy Hungd1c74342015-07-07 16:54:23 -07001585 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001586 if (mTrack == 0) return NO_INIT;
1587 return mTrack->setParameters(keyValuePairs);
1588}
1589
1590String8 MediaPlayerService::AudioOutput::getParameters(const String8& keys)
1591{
Andy Hungd1c74342015-07-07 16:54:23 -07001592 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001593 if (mTrack == 0) return String8::empty();
1594 return mTrack->getParameters(keys);
1595}
1596
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001597void MediaPlayerService::AudioOutput::setAudioAttributes(const audio_attributes_t * attributes) {
Andy Hungd1c74342015-07-07 16:54:23 -07001598 Mutex::Autolock lock(mLock);
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001599 if (attributes == NULL) {
1600 free(mAttributes);
1601 mAttributes = NULL;
1602 } else {
1603 if (mAttributes == NULL) {
1604 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1605 }
1606 memcpy(mAttributes, attributes, sizeof(audio_attributes_t));
Eric Laurent43562692015-07-15 16:49:07 -07001607 mStreamType = audio_attributes_to_stream_type(attributes);
1608 }
1609}
1610
1611void MediaPlayerService::AudioOutput::setAudioStreamType(audio_stream_type_t streamType)
1612{
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001613 Mutex::Autolock lock(mLock);
Eric Laurent43562692015-07-15 16:49:07 -07001614 // do not allow direct stream type modification if attributes have been set
1615 if (mAttributes == NULL) {
1616 mStreamType = streamType;
1617 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001618}
1619
Andy Hungd1c74342015-07-07 16:54:23 -07001620void MediaPlayerService::AudioOutput::deleteRecycledTrack_l()
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001621{
Andy Hungd1c74342015-07-07 16:54:23 -07001622 ALOGV("deleteRecycledTrack_l");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001623 if (mRecycledTrack != 0) {
1624
1625 if (mCallbackData != NULL) {
1626 mCallbackData->setOutput(NULL);
1627 mCallbackData->endTrackSwitch();
1628 }
1629
1630 if ((mRecycledTrack->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) {
Andy Hunge13f8a62016-03-30 14:20:42 -07001631 int32_t msec = 0;
1632 if (!mRecycledTrack->stopped()) { // check if active
1633 (void)mRecycledTrack->pendingDuration(&msec);
1634 }
1635 mRecycledTrack->stop(); // ensure full data drain
1636 ALOGD("deleting recycled track, waiting for data drain (%d msec)", msec);
1637 if (msec > 0) {
1638 static const int32_t WAIT_LIMIT_MS = 3000;
1639 if (msec > WAIT_LIMIT_MS) {
1640 msec = WAIT_LIMIT_MS;
1641 }
1642 usleep(msec * 1000LL);
1643 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001644 }
1645 // An offloaded track isn't flushed because the STREAM_END is reported
1646 // slightly prematurely to allow time for the gapless track switch
1647 // but this means that if we decide not to recycle the track there
1648 // could be a small amount of residual data still playing. We leave
1649 // AudioFlinger to drain the track.
1650
1651 mRecycledTrack.clear();
Andy Hungd1c74342015-07-07 16:54:23 -07001652 close_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001653 delete mCallbackData;
1654 mCallbackData = NULL;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001655 }
1656}
1657
Andy Hungd1c74342015-07-07 16:54:23 -07001658void MediaPlayerService::AudioOutput::close_l()
1659{
1660 mTrack.clear();
1661}
1662
Andreas Huber20111aa2009-07-14 16:56:47 -07001663status_t MediaPlayerService::AudioOutput::open(
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001664 uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
1665 audio_format_t format, int bufferCount,
Eric Laurent1948eb32012-04-13 16:50:19 -07001666 AudioCallback cb, void *cookie,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001667 audio_output_flags_t flags,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001668 const audio_offload_info_t *offloadInfo,
Andy Hung179652e2015-05-31 22:49:46 -07001669 bool doNotReconnect,
1670 uint32_t suggestedFrameCount)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001671{
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001672 ALOGV("open(%u, %d, 0x%x, 0x%x, %d, %d 0x%x)", sampleRate, channelCount, channelMask,
1673 format, bufferCount, mSessionId, flags);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001674
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001675 // offloading is only supported in callback mode for now.
1676 // offloadInfo must be present if offload flag is set
1677 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) &&
1678 ((cb == NULL) || (offloadInfo == NULL))) {
1679 return BAD_VALUE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001680 }
1681
Andy Hung179652e2015-05-31 22:49:46 -07001682 // compute frame count for the AudioTrack internal buffer
1683 size_t frameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001684 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1685 frameCount = 0; // AudioTrack will get frame count from AudioFlinger
1686 } else {
Andy Hung179652e2015-05-31 22:49:46 -07001687 // try to estimate the buffer processing fetch size from AudioFlinger.
1688 // framesPerBuffer is approximate and generally correct, except when it's not :-).
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001689 uint32_t afSampleRate;
1690 size_t afFrameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001691 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1692 return NO_INIT;
1693 }
1694 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1695 return NO_INIT;
1696 }
Andy Hung179652e2015-05-31 22:49:46 -07001697 const size_t framesPerBuffer =
1698 (unsigned long long)sampleRate * afFrameCount / afSampleRate;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001699
Andy Hung179652e2015-05-31 22:49:46 -07001700 if (bufferCount == 0) {
1701 // use suggestedFrameCount
1702 bufferCount = (suggestedFrameCount + framesPerBuffer - 1) / framesPerBuffer;
1703 }
1704 // Check argument bufferCount against the mininum buffer count
1705 if (bufferCount != 0 && bufferCount < mMinBufferCount) {
1706 ALOGV("bufferCount (%d) increased to %d", bufferCount, mMinBufferCount);
1707 bufferCount = mMinBufferCount;
1708 }
1709 // if frameCount is 0, then AudioTrack will get frame count from AudioFlinger
1710 // which will be the minimum size permitted.
1711 frameCount = bufferCount * framesPerBuffer;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001712 }
Andreas Huber20111aa2009-07-14 16:56:47 -07001713
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001714 if (channelMask == CHANNEL_MASK_USE_CHANNEL_ORDER) {
Glenn Kastenab334fd2012-03-14 12:56:06 -07001715 channelMask = audio_channel_out_mask_from_count(channelCount);
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001716 if (0 == channelMask) {
1717 ALOGE("open() error, can\'t derive mask for %d audio channels", channelCount);
1718 return NO_INIT;
1719 }
1720 }
Eric Laurent1948eb32012-04-13 16:50:19 -07001721
Andy Hungd1c74342015-07-07 16:54:23 -07001722 Mutex::Autolock lock(mLock);
Andy Hung179652e2015-05-31 22:49:46 -07001723 mCallback = cb;
1724 mCallbackCookie = cookie;
1725
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001726 // Check whether we can recycle the track
1727 bool reuse = false;
1728 bool bothOffloaded = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001729
Glenn Kasten2799d742013-05-30 14:33:29 -07001730 if (mRecycledTrack != 0) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001731 // check whether we are switching between two offloaded tracks
1732 bothOffloaded = (flags & mRecycledTrack->getFlags()
1733 & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0;
Marco Nelissen67295b52012-06-11 14:52:53 -07001734
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001735 // check if the existing track can be reused as-is, or if a new track needs to be created.
1736 reuse = true;
1737
Marco Nelissen67295b52012-06-11 14:52:53 -07001738 if ((mCallbackData == NULL && mCallback != NULL) ||
1739 (mCallbackData != NULL && mCallback == NULL)) {
1740 // recycled track uses callbacks but the caller wants to use writes, or vice versa
1741 ALOGV("can't chain callback and write");
1742 reuse = false;
1743 } else if ((mRecycledTrack->getSampleRate() != sampleRate) ||
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001744 (mRecycledTrack->channelCount() != (uint32_t)channelCount) ) {
1745 ALOGV("samplerate, channelcount differ: %u/%u Hz, %u/%d ch",
Marco Nelissen67295b52012-06-11 14:52:53 -07001746 mRecycledTrack->getSampleRate(), sampleRate,
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001747 mRecycledTrack->channelCount(), channelCount);
Marco Nelissen67295b52012-06-11 14:52:53 -07001748 reuse = false;
1749 } else if (flags != mFlags) {
1750 ALOGV("output flags differ %08x/%08x", flags, mFlags);
1751 reuse = false;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001752 } else if (mRecycledTrack->format() != format) {
1753 reuse = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001754 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001755 } else {
1756 ALOGV("no track available to recycle");
1757 }
1758
1759 ALOGV_IF(bothOffloaded, "both tracks offloaded");
1760
1761 // If we can't recycle and both tracks are offloaded
1762 // we must close the previous output before opening a new one
1763 if (bothOffloaded && !reuse) {
1764 ALOGV("both offloaded and not recycling");
Andy Hungd1c74342015-07-07 16:54:23 -07001765 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001766 }
1767
1768 sp<AudioTrack> t;
1769 CallbackData *newcbd = NULL;
1770
1771 // We don't attempt to create a new track if we are recycling an
1772 // offloaded track. But, if we are recycling a non-offloaded or we
1773 // are switching where one is offloaded and one isn't then we create
1774 // the new track in advance so that we can read additional stream info
1775
1776 if (!(reuse && bothOffloaded)) {
1777 ALOGV("creating new AudioTrack");
1778
1779 if (mCallback != NULL) {
1780 newcbd = new CallbackData(this);
1781 t = new AudioTrack(
1782 mStreamType,
1783 sampleRate,
1784 format,
1785 channelMask,
1786 frameCount,
1787 flags,
1788 CallbackWrapper,
1789 newcbd,
1790 0, // notification frames
1791 mSessionId,
1792 AudioTrack::TRANSFER_CALLBACK,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001793 offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -08001794 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001795 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001796 mAttributes,
1797 doNotReconnect);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001798 } else {
Andy Hungff874dc2016-04-11 16:49:09 -07001799 // TODO: Due to buffer memory concerns, we use a max target playback speed
1800 // based on mPlaybackRate at the time of open (instead of kMaxRequiredSpeed),
1801 // also clamping the target speed to 1.0 <= targetSpeed <= kMaxRequiredSpeed.
1802 const float targetSpeed =
1803 std::min(std::max(mPlaybackRate.mSpeed, 1.0f), kMaxRequiredSpeed);
1804 ALOGW_IF(targetSpeed != mPlaybackRate.mSpeed,
1805 "track target speed:%f clamped from playback speed:%f",
1806 targetSpeed, mPlaybackRate.mSpeed);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001807 t = new AudioTrack(
1808 mStreamType,
1809 sampleRate,
1810 format,
1811 channelMask,
1812 frameCount,
1813 flags,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001814 NULL, // callback
1815 NULL, // user data
1816 0, // notification frames
1817 mSessionId,
1818 AudioTrack::TRANSFER_DEFAULT,
1819 NULL, // offload info
Marco Nelissend457c972014-02-11 08:47:07 -08001820 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001821 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001822 mAttributes,
Andy Hungff874dc2016-04-11 16:49:09 -07001823 doNotReconnect,
1824 targetSpeed);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001825 }
1826
1827 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1828 ALOGE("Unable to create audio track");
1829 delete newcbd;
Glenn Kasten3e98ecd2015-05-18 13:13:24 -07001830 // t goes out of scope, so reference count drops to zero
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001831 return NO_INIT;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001832 } else {
1833 // successful AudioTrack initialization implies a legacy stream type was generated
1834 // from the audio attributes
1835 mStreamType = t->streamType();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001836 }
1837 }
1838
1839 if (reuse) {
1840 CHECK(mRecycledTrack != NULL);
1841
1842 if (!bothOffloaded) {
1843 if (mRecycledTrack->frameCount() != t->frameCount()) {
Andy Hung833b4752016-04-04 17:15:48 -07001844 ALOGV("framecount differs: %zu/%zu frames",
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001845 mRecycledTrack->frameCount(), t->frameCount());
1846 reuse = false;
1847 }
1848 }
1849
Marco Nelissen67295b52012-06-11 14:52:53 -07001850 if (reuse) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001851 ALOGV("chaining to next output and recycling track");
Andy Hungd1c74342015-07-07 16:54:23 -07001852 close_l();
Marco Nelissen67295b52012-06-11 14:52:53 -07001853 mTrack = mRecycledTrack;
Glenn Kasten2799d742013-05-30 14:33:29 -07001854 mRecycledTrack.clear();
Marco Nelissen67295b52012-06-11 14:52:53 -07001855 if (mCallbackData != NULL) {
1856 mCallbackData->setOutput(this);
1857 }
Marco Nelissen67295b52012-06-11 14:52:53 -07001858 delete newcbd;
1859 return OK;
1860 }
Marco Nelissen67295b52012-06-11 14:52:53 -07001861 }
1862
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001863 // we're not going to reuse the track, unblock and flush it
1864 // this was done earlier if both tracks are offloaded
1865 if (!bothOffloaded) {
Andy Hungd1c74342015-07-07 16:54:23 -07001866 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001867 }
1868
1869 CHECK((t != NULL) && ((mCallback == NULL) || (newcbd != NULL)));
1870
Marco Nelissen67295b52012-06-11 14:52:53 -07001871 mCallbackData = newcbd;
Steve Block3856b092011-10-20 11:56:00 +01001872 ALOGV("setVolume");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001873 t->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07001874
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001875 mSampleRateHz = sampleRate;
Preetam Singh Ranawat2e17eef2015-08-12 12:11:46 -07001876 mFlags = flags;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001877 mMsecsPerFrame = 1E3f / (mPlaybackRate.mSpeed * sampleRate);
Andy Hungd1c74342015-07-07 16:54:23 -07001878 mFrameSize = t->frameSize();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001879 mTrack = t;
Eric Laurent2beeb502010-07-16 07:43:46 -07001880
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001881 status_t res = NO_ERROR;
Wei Jia0162d002015-06-09 11:59:33 -07001882 // Note some output devices may give us a direct track even though we don't specify it.
1883 // Example: Line application b/17459982.
Preetam Singh Ranawat2e17eef2015-08-12 12:11:46 -07001884 if ((t->getFlags() & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) {
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001885 res = t->setPlaybackRate(mPlaybackRate);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001886 if (res == NO_ERROR) {
1887 t->setAuxEffectSendLevel(mSendLevel);
1888 res = t->attachAuxEffect(mAuxEffectId);
1889 }
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001890 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001891 ALOGV("open() DONE status %d", res);
1892 return res;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001893}
1894
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001895status_t MediaPlayerService::AudioOutput::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001896{
Steve Block3856b092011-10-20 11:56:00 +01001897 ALOGV("start");
Andy Hungd1c74342015-07-07 16:54:23 -07001898 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001899 if (mCallbackData != NULL) {
1900 mCallbackData->endTrackSwitch();
1901 }
Glenn Kasten2799d742013-05-30 14:33:29 -07001902 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001903 mTrack->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07001904 mTrack->setAuxEffectSendLevel(mSendLevel);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001905 return mTrack->start();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001906 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001907 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001908}
1909
Marco Nelissen6b74d672012-02-28 16:07:44 -08001910void MediaPlayerService::AudioOutput::setNextOutput(const sp<AudioOutput>& nextOutput) {
Andy Hungd1c74342015-07-07 16:54:23 -07001911 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001912 mNextOutput = nextOutput;
1913}
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08001914
Marco Nelissen6b74d672012-02-28 16:07:44 -08001915void MediaPlayerService::AudioOutput::switchToNextOutput() {
1916 ALOGV("switchToNextOutput");
Andy Hungd1c74342015-07-07 16:54:23 -07001917
1918 // Try to acquire the callback lock before moving track (without incurring deadlock).
1919 const unsigned kMaxSwitchTries = 100;
1920 Mutex::Autolock lock(mLock);
1921 for (unsigned tries = 0;;) {
1922 if (mTrack == 0) {
1923 return;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001924 }
Andy Hungd1c74342015-07-07 16:54:23 -07001925 if (mNextOutput != NULL && mNextOutput != this) {
1926 if (mCallbackData != NULL) {
1927 // two alternative approaches
1928#if 1
1929 CallbackData *callbackData = mCallbackData;
1930 mLock.unlock();
1931 // proper acquisition sequence
1932 callbackData->lock();
1933 mLock.lock();
1934 // Caution: it is unlikely that someone deleted our callback or changed our target
1935 if (callbackData != mCallbackData || mNextOutput == NULL || mNextOutput == this) {
1936 // fatal if we are starved out.
1937 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
1938 "switchToNextOutput() cannot obtain correct lock sequence");
1939 callbackData->unlock();
1940 continue;
1941 }
1942 callbackData->mSwitching = true; // begin track switch
1943#else
1944 // tryBeginTrackSwitch() returns false if the callback has the lock.
1945 if (!mCallbackData->tryBeginTrackSwitch()) {
1946 // fatal if we are starved out.
1947 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
1948 "switchToNextOutput() cannot obtain callback lock");
1949 mLock.unlock();
1950 usleep(5 * 1000 /* usec */); // allow callback to use AudioOutput
1951 mLock.lock();
1952 continue;
1953 }
1954#endif
1955 }
1956
1957 Mutex::Autolock nextLock(mNextOutput->mLock);
1958
1959 // If the next output track is not NULL, then it has been
1960 // opened already for playback.
1961 // This is possible even without the next player being started,
1962 // for example, the next player could be prepared and seeked.
1963 //
1964 // Presuming it isn't advisable to force the track over.
1965 if (mNextOutput->mTrack == NULL) {
1966 ALOGD("Recycling track for gapless playback");
1967 delete mNextOutput->mCallbackData;
1968 mNextOutput->mCallbackData = mCallbackData;
1969 mNextOutput->mRecycledTrack = mTrack;
1970 mNextOutput->mSampleRateHz = mSampleRateHz;
1971 mNextOutput->mMsecsPerFrame = mMsecsPerFrame;
Andy Hungd1c74342015-07-07 16:54:23 -07001972 mNextOutput->mFlags = mFlags;
1973 mNextOutput->mFrameSize = mFrameSize;
1974 close_l();
1975 mCallbackData = NULL; // destruction handled by mNextOutput
1976 } else {
1977 ALOGW("Ignoring gapless playback because next player has already started");
1978 // remove track in case resource needed for future players.
1979 if (mCallbackData != NULL) {
1980 mCallbackData->endTrackSwitch(); // release lock for callbacks before close.
1981 }
1982 close_l();
1983 }
1984 }
1985 break;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001986 }
1987}
1988
Wei Jia7d3f4df2015-03-03 15:28:00 -08001989ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001990{
Andy Hungd1c74342015-07-07 16:54:23 -07001991 Mutex::Autolock lock(mLock);
Glenn Kastenadad3d72014-02-21 14:51:43 -08001992 LOG_ALWAYS_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
Andreas Huber20111aa2009-07-14 16:56:47 -07001993
Steve Block3856b092011-10-20 11:56:00 +01001994 //ALOGV("write(%p, %u)", buffer, size);
Glenn Kasten2799d742013-05-30 14:33:29 -07001995 if (mTrack != 0) {
Andy Hung2f6e73d2016-04-08 12:12:58 -07001996 return mTrack->write(buffer, size, blocking);
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001997 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001998 return NO_INIT;
1999}
2000
2001void MediaPlayerService::AudioOutput::stop()
2002{
Steve Block3856b092011-10-20 11:56:00 +01002003 ALOGV("stop");
Andy Hungd1c74342015-07-07 16:54:23 -07002004 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002005 if (mTrack != 0) mTrack->stop();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002006}
2007
2008void MediaPlayerService::AudioOutput::flush()
2009{
Steve Block3856b092011-10-20 11:56:00 +01002010 ALOGV("flush");
Andy Hungd1c74342015-07-07 16:54:23 -07002011 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002012 if (mTrack != 0) mTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002013}
2014
2015void MediaPlayerService::AudioOutput::pause()
2016{
Steve Block3856b092011-10-20 11:56:00 +01002017 ALOGV("pause");
Andy Hungd1c74342015-07-07 16:54:23 -07002018 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002019 if (mTrack != 0) mTrack->pause();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002020}
2021
2022void MediaPlayerService::AudioOutput::close()
2023{
Steve Block3856b092011-10-20 11:56:00 +01002024 ALOGV("close");
Erik Wolsheimer7845a1f2015-10-30 12:07:52 -07002025 sp<AudioTrack> track;
2026 {
2027 Mutex::Autolock lock(mLock);
2028 track = mTrack;
2029 close_l(); // clears mTrack
2030 }
2031 // destruction of the track occurs outside of mutex.
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002032}
2033
2034void MediaPlayerService::AudioOutput::setVolume(float left, float right)
2035{
Steve Block3856b092011-10-20 11:56:00 +01002036 ALOGV("setVolume(%f, %f)", left, right);
Andy Hungd1c74342015-07-07 16:54:23 -07002037 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002038 mLeftVolume = left;
2039 mRightVolume = right;
Glenn Kasten2799d742013-05-30 14:33:29 -07002040 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002041 mTrack->setVolume(left, right);
2042 }
2043}
2044
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002045status_t MediaPlayerService::AudioOutput::setPlaybackRate(const AudioPlaybackRate &rate)
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002046{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002047 ALOGV("setPlaybackRate(%f %f %d %d)",
2048 rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Andy Hungd1c74342015-07-07 16:54:23 -07002049 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002050 if (mTrack == 0) {
2051 // remember rate so that we can set it when the track is opened
2052 mPlaybackRate = rate;
2053 return OK;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002054 }
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002055 status_t res = mTrack->setPlaybackRate(rate);
2056 if (res != NO_ERROR) {
2057 return res;
2058 }
2059 // rate.mSpeed is always greater than 0 if setPlaybackRate succeeded
2060 CHECK_GT(rate.mSpeed, 0.f);
2061 mPlaybackRate = rate;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002062 if (mSampleRateHz != 0) {
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002063 mMsecsPerFrame = 1E3f / (rate.mSpeed * mSampleRateHz);
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002064 }
2065 return res;
2066}
2067
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002068status_t MediaPlayerService::AudioOutput::getPlaybackRate(AudioPlaybackRate *rate)
2069{
2070 ALOGV("setPlaybackRate");
Andy Hungd1c74342015-07-07 16:54:23 -07002071 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002072 if (mTrack == 0) {
2073 return NO_INIT;
2074 }
2075 *rate = mTrack->getPlaybackRate();
2076 return NO_ERROR;
2077}
2078
Eric Laurent2beeb502010-07-16 07:43:46 -07002079status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
2080{
Steve Block3856b092011-10-20 11:56:00 +01002081 ALOGV("setAuxEffectSendLevel(%f)", level);
Andy Hungd1c74342015-07-07 16:54:23 -07002082 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002083 mSendLevel = level;
Glenn Kasten2799d742013-05-30 14:33:29 -07002084 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002085 return mTrack->setAuxEffectSendLevel(level);
2086 }
2087 return NO_ERROR;
2088}
2089
2090status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
2091{
Steve Block3856b092011-10-20 11:56:00 +01002092 ALOGV("attachAuxEffect(%d)", effectId);
Andy Hungd1c74342015-07-07 16:54:23 -07002093 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002094 mAuxEffectId = effectId;
Glenn Kasten2799d742013-05-30 14:33:29 -07002095 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002096 return mTrack->attachAuxEffect(effectId);
2097 }
2098 return NO_ERROR;
2099}
2100
Andreas Huber20111aa2009-07-14 16:56:47 -07002101// static
2102void MediaPlayerService::AudioOutput::CallbackWrapper(
Glenn Kastend217a8c2011-06-01 15:20:35 -07002103 int event, void *cookie, void *info) {
Steve Block3856b092011-10-20 11:56:00 +01002104 //ALOGV("callbackwrapper");
Marco Nelissen6b74d672012-02-28 16:07:44 -08002105 CallbackData *data = (CallbackData*)cookie;
Andy Hungd1c74342015-07-07 16:54:23 -07002106 // lock to ensure we aren't caught in the middle of a track switch.
Marco Nelissen6b74d672012-02-28 16:07:44 -08002107 data->lock();
2108 AudioOutput *me = data->getOutput();
Andreas Huber20111aa2009-07-14 16:56:47 -07002109 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002110 if (me == NULL) {
2111 // no output set, likely because the track was scheduled to be reused
2112 // by another player, but the format turned out to be incompatible.
2113 data->unlock();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002114 if (buffer != NULL) {
2115 buffer->size = 0;
2116 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08002117 return;
2118 }
Andreas Huber20111aa2009-07-14 16:56:47 -07002119
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002120 switch(event) {
2121 case AudioTrack::EVENT_MORE_DATA: {
2122 size_t actualSize = (*me->mCallback)(
2123 me, buffer->raw, buffer->size, me->mCallbackCookie,
2124 CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002125
Andy Hung719b46b2015-05-31 22:18:25 -07002126 // Log when no data is returned from the callback.
2127 // (1) We may have no data (especially with network streaming sources).
2128 // (2) We may have reached the EOS and the audio track is not stopped yet.
2129 // Note that AwesomePlayer/AudioPlayer will only return zero size when it reaches the EOS.
2130 // NuPlayerRenderer will return zero when it doesn't have data (it doesn't block to fill).
2131 //
2132 // This is a benign busy-wait, with the next data request generated 10 ms or more later;
2133 // nevertheless for power reasons, we don't want to see too many of these.
Andreas Huber2e8ffaf2010-02-18 16:45:13 -08002134
Andy Hung719b46b2015-05-31 22:18:25 -07002135 ALOGV_IF(actualSize == 0 && buffer->size > 0, "callbackwrapper: empty buffer returned");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002136
2137 buffer->size = actualSize;
2138 } break;
2139
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002140 case AudioTrack::EVENT_STREAM_END:
Andy Hung719b46b2015-05-31 22:18:25 -07002141 // currently only occurs for offloaded callbacks
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002142 ALOGV("callbackwrapper: deliver EVENT_STREAM_END");
2143 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2144 me->mCallbackCookie, CB_EVENT_STREAM_END);
2145 break;
2146
2147 case AudioTrack::EVENT_NEW_IAUDIOTRACK :
2148 ALOGV("callbackwrapper: deliver EVENT_TEAR_DOWN");
2149 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2150 me->mCallbackCookie, CB_EVENT_TEAR_DOWN);
2151 break;
2152
Glenn Kasten421743b2015-06-01 08:18:08 -07002153 case AudioTrack::EVENT_UNDERRUN:
Andy Hung719b46b2015-05-31 22:18:25 -07002154 // This occurs when there is no data available, typically
Glenn Kasten421743b2015-06-01 08:18:08 -07002155 // when there is a failure to supply data to the AudioTrack. It can also
2156 // occur in non-offloaded mode when the audio device comes out of standby.
2157 //
Andy Hung719b46b2015-05-31 22:18:25 -07002158 // If an AudioTrack underruns it outputs silence. Since this happens suddenly
2159 // it may sound like an audible pop or glitch.
2160 //
2161 // The underrun event is sent once per track underrun; the condition is reset
2162 // when more data is sent to the AudioTrack.
Glenn Kasten421743b2015-06-01 08:18:08 -07002163 ALOGI("callbackwrapper: EVENT_UNDERRUN (discarded)");
2164 break;
2165
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002166 default:
2167 ALOGE("received unknown event type: %d inside CallbackWrapper !", event);
Andreas Huber51c1e0e2011-04-04 11:43:40 -07002168 }
2169
Marco Nelissen6b74d672012-02-28 16:07:44 -08002170 data->unlock();
Andreas Huber20111aa2009-07-14 16:56:47 -07002171}
2172
Glenn Kastend848eb42016-03-08 13:42:11 -08002173audio_session_t MediaPlayerService::AudioOutput::getSessionId() const
Eric Laurent8c563ed2010-10-07 18:23:03 -07002174{
Andy Hungd1c74342015-07-07 16:54:23 -07002175 Mutex::Autolock lock(mLock);
Eric Laurent8c563ed2010-10-07 18:23:03 -07002176 return mSessionId;
2177}
2178
Eric Laurent6f59db12013-07-26 17:16:50 -07002179uint32_t MediaPlayerService::AudioOutput::getSampleRate() const
2180{
Andy Hungd1c74342015-07-07 16:54:23 -07002181 Mutex::Autolock lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -07002182 if (mTrack == 0) return 0;
2183 return mTrack->getSampleRate();
2184}
2185
Andy Hungf2c87b32016-04-07 19:49:29 -07002186int64_t MediaPlayerService::AudioOutput::getBufferDurationInUs() const
2187{
2188 Mutex::Autolock lock(mLock);
2189 if (mTrack == 0) {
2190 return 0;
2191 }
2192 int64_t duration;
2193 if (mTrack->getBufferDurationInUs(&duration) != OK) {
2194 return 0;
2195 }
2196 return duration;
2197}
2198
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002199////////////////////////////////////////////////////////////////////////////////
2200
2201struct CallbackThread : public Thread {
2202 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
2203 MediaPlayerBase::AudioSink::AudioCallback cb,
2204 void *cookie);
2205
2206protected:
2207 virtual ~CallbackThread();
2208
2209 virtual bool threadLoop();
2210
2211private:
2212 wp<MediaPlayerBase::AudioSink> mSink;
2213 MediaPlayerBase::AudioSink::AudioCallback mCallback;
2214 void *mCookie;
2215 void *mBuffer;
2216 size_t mBufferSize;
2217
2218 CallbackThread(const CallbackThread &);
2219 CallbackThread &operator=(const CallbackThread &);
2220};
2221
2222CallbackThread::CallbackThread(
2223 const wp<MediaPlayerBase::AudioSink> &sink,
2224 MediaPlayerBase::AudioSink::AudioCallback cb,
2225 void *cookie)
2226 : mSink(sink),
2227 mCallback(cb),
2228 mCookie(cookie),
2229 mBuffer(NULL),
2230 mBufferSize(0) {
2231}
2232
2233CallbackThread::~CallbackThread() {
2234 if (mBuffer) {
2235 free(mBuffer);
2236 mBuffer = NULL;
2237 }
2238}
2239
2240bool CallbackThread::threadLoop() {
2241 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
2242 if (sink == NULL) {
2243 return false;
2244 }
2245
2246 if (mBuffer == NULL) {
2247 mBufferSize = sink->bufferSize();
2248 mBuffer = malloc(mBufferSize);
2249 }
2250
2251 size_t actualSize =
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002252 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie,
2253 MediaPlayerBase::AudioSink::CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002254
2255 if (actualSize > 0) {
2256 sink->write(mBuffer, actualSize);
Andy Hunga31335a2014-08-20 17:37:59 -07002257 // Could return false on sink->write() error or short count.
2258 // Not necessarily appropriate but would work for AudioCache behavior.
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002259 }
2260
2261 return true;
2262}
2263
2264////////////////////////////////////////////////////////////////////////////////
2265
Gloria Wang7cf180c2011-02-19 18:37:57 -08002266void MediaPlayerService::addBatteryData(uint32_t params)
2267{
2268 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002269
2270 int32_t time = systemTime() / 1000000L;
2271
2272 // change audio output devices. This notification comes from AudioFlinger
2273 if ((params & kBatteryDataSpeakerOn)
2274 || (params & kBatteryDataOtherAudioDeviceOn)) {
2275
2276 int deviceOn[NUM_AUDIO_DEVICES];
2277 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2278 deviceOn[i] = 0;
2279 }
2280
2281 if ((params & kBatteryDataSpeakerOn)
2282 && (params & kBatteryDataOtherAudioDeviceOn)) {
2283 deviceOn[SPEAKER_AND_OTHER] = 1;
2284 } else if (params & kBatteryDataSpeakerOn) {
2285 deviceOn[SPEAKER] = 1;
2286 } else {
2287 deviceOn[OTHER_AUDIO_DEVICE] = 1;
2288 }
2289
2290 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2291 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
2292
2293 if (mBatteryAudio.refCount > 0) { // if playing audio
2294 if (!deviceOn[i]) {
2295 mBatteryAudio.lastTime[i] += time;
2296 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2297 mBatteryAudio.lastTime[i] = 0;
2298 } else {
2299 mBatteryAudio.lastTime[i] = 0 - time;
2300 }
2301 }
2302
2303 mBatteryAudio.deviceOn[i] = deviceOn[i];
2304 }
2305 }
2306 return;
2307 }
2308
Marco Nelissenb7848f12014-12-04 08:57:56 -08002309 // an audio stream is started
Gloria Wang9ee159b2011-02-24 14:51:45 -08002310 if (params & kBatteryDataAudioFlingerStart) {
2311 // record the start time only if currently no other audio
2312 // is being played
2313 if (mBatteryAudio.refCount == 0) {
2314 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2315 if (mBatteryAudio.deviceOn[i]) {
2316 mBatteryAudio.lastTime[i] -= time;
2317 }
2318 }
2319 }
2320
2321 mBatteryAudio.refCount ++;
2322 return;
2323
2324 } else if (params & kBatteryDataAudioFlingerStop) {
2325 if (mBatteryAudio.refCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002326 ALOGW("Battery track warning: refCount is <= 0");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002327 return;
2328 }
2329
2330 // record the stop time only if currently this is the only
2331 // audio being played
2332 if (mBatteryAudio.refCount == 1) {
2333 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2334 if (mBatteryAudio.deviceOn[i]) {
2335 mBatteryAudio.lastTime[i] += time;
2336 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2337 mBatteryAudio.lastTime[i] = 0;
2338 }
2339 }
2340 }
2341
2342 mBatteryAudio.refCount --;
2343 return;
2344 }
2345
Gloria Wang7cf180c2011-02-19 18:37:57 -08002346 int uid = IPCThreadState::self()->getCallingUid();
2347 if (uid == AID_MEDIA) {
2348 return;
2349 }
2350 int index = mBatteryData.indexOfKey(uid);
Gloria Wang7cf180c2011-02-19 18:37:57 -08002351
2352 if (index < 0) { // create a new entry for this UID
2353 BatteryUsageInfo info;
2354 info.audioTotalTime = 0;
2355 info.videoTotalTime = 0;
2356 info.audioLastTime = 0;
2357 info.videoLastTime = 0;
2358 info.refCount = 0;
2359
Gloria Wang9ee159b2011-02-24 14:51:45 -08002360 if (mBatteryData.add(uid, info) == NO_MEMORY) {
Steve Block29357bc2012-01-06 19:20:56 +00002361 ALOGE("Battery track error: no memory for new app");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002362 return;
2363 }
Gloria Wang7cf180c2011-02-19 18:37:57 -08002364 }
2365
2366 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
2367
2368 if (params & kBatteryDataCodecStarted) {
2369 if (params & kBatteryDataTrackAudio) {
2370 info.audioLastTime -= time;
2371 info.refCount ++;
2372 }
2373 if (params & kBatteryDataTrackVideo) {
2374 info.videoLastTime -= time;
2375 info.refCount ++;
2376 }
2377 } else {
2378 if (info.refCount == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002379 ALOGW("Battery track warning: refCount is already 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002380 return;
2381 } else if (info.refCount < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00002382 ALOGE("Battery track error: refCount < 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002383 mBatteryData.removeItem(uid);
2384 return;
2385 }
2386
2387 if (params & kBatteryDataTrackAudio) {
2388 info.audioLastTime += time;
2389 info.refCount --;
2390 }
2391 if (params & kBatteryDataTrackVideo) {
2392 info.videoLastTime += time;
2393 info.refCount --;
2394 }
2395
2396 // no stream is being played by this UID
2397 if (info.refCount == 0) {
2398 info.audioTotalTime += info.audioLastTime;
2399 info.audioLastTime = 0;
2400 info.videoTotalTime += info.videoLastTime;
2401 info.videoLastTime = 0;
2402 }
2403 }
2404}
2405
2406status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
2407 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002408
2409 // audio output devices usage
2410 int32_t time = systemTime() / 1000000L; //in ms
2411 int32_t totalTime;
2412
2413 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2414 totalTime = mBatteryAudio.totalTime[i];
2415
2416 if (mBatteryAudio.deviceOn[i]
2417 && (mBatteryAudio.lastTime[i] != 0)) {
2418 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
2419 totalTime += tmpTime;
2420 }
2421
2422 reply->writeInt32(totalTime);
2423 // reset the total time
2424 mBatteryAudio.totalTime[i] = 0;
2425 }
2426
2427 // codec usage
Gloria Wang7cf180c2011-02-19 18:37:57 -08002428 BatteryUsageInfo info;
2429 int size = mBatteryData.size();
2430
2431 reply->writeInt32(size);
2432 int i = 0;
2433
2434 while (i < size) {
2435 info = mBatteryData.valueAt(i);
2436
2437 reply->writeInt32(mBatteryData.keyAt(i)); //UID
2438 reply->writeInt32(info.audioTotalTime);
2439 reply->writeInt32(info.videoTotalTime);
2440
2441 info.audioTotalTime = 0;
2442 info.videoTotalTime = 0;
2443
2444 // remove the UID entry where no stream is being played
2445 if (info.refCount <= 0) {
2446 mBatteryData.removeItemsAt(i);
2447 size --;
2448 i --;
2449 }
2450 i++;
2451 }
2452 return NO_ERROR;
2453}
nikoa64c8c72009-07-20 15:07:26 -07002454} // namespace android