blob: 6e689e6a92cf733daeeffc9162ab856803216435 [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 Huber59451f82012-09-18 10:36:32 -070081#include "HDCP.h"
Andreas Huberb7319a72013-05-29 14:20:52 -070082#include "HTTPBase.h"
Andreas Huber35213f12012-08-29 11:41:50 -070083#include "RemoteDisplay.h"
Andreas Hubered3e3e02012-03-26 11:13:27 -070084
Wei Jia502c2f42017-07-13 17:47:56 -070085static const int kDumpLockRetries = 50;
86static const int kDumpLockSleepUs = 20000;
87
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070088namespace {
nikoa64c8c72009-07-20 15:07:26 -070089using android::media::Metadata;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070090using android::status_t;
91using android::OK;
92using android::BAD_VALUE;
93using android::NOT_ENOUGH_DATA;
94using android::Parcel;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070095
96// Max number of entries in the filter.
97const int kMaxFilterSize = 64; // I pulled that out of thin air.
98
Andy Hungff874dc2016-04-11 16:49:09 -070099const float kMaxRequiredSpeed = 8.0f; // for PCM tracks allow up to 8x speedup.
100
nikoa64c8c72009-07-20 15:07:26 -0700101// FIXME: Move all the metadata related function in the Metadata.cpp
nikod608a812009-07-16 16:39:53 -0700102
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700103
104// Unmarshall a filter from a Parcel.
105// Filter format in a parcel:
106//
107// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
108// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
109// | number of entries (n) |
110// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
111// | metadata type 1 |
112// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
113// | metadata type 2 |
114// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
115// ....
116// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
117// | metadata type n |
118// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
119//
120// @param p Parcel that should start with a filter.
121// @param[out] filter On exit contains the list of metadata type to be
122// filtered.
123// @param[out] status On exit contains the status code to be returned.
124// @return true if the parcel starts with a valid filter.
125bool unmarshallFilter(const Parcel& p,
nikoa64c8c72009-07-20 15:07:26 -0700126 Metadata::Filter *filter,
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700127 status_t *status)
128{
Nicolas Catania48290382009-07-10 13:53:06 -0700129 int32_t val;
130 if (p.readInt32(&val) != OK)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700131 {
Steve Block29357bc2012-01-06 19:20:56 +0000132 ALOGE("Failed to read filter's length");
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700133 *status = NOT_ENOUGH_DATA;
134 return false;
135 }
136
Nicolas Catania48290382009-07-10 13:53:06 -0700137 if( val > kMaxFilterSize || val < 0)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700138 {
Steve Block29357bc2012-01-06 19:20:56 +0000139 ALOGE("Invalid filter len %d", val);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700140 *status = BAD_VALUE;
141 return false;
142 }
143
Nicolas Catania48290382009-07-10 13:53:06 -0700144 const size_t num = val;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700145
146 filter->clear();
Nicolas Catania48290382009-07-10 13:53:06 -0700147 filter->setCapacity(num);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700148
nikoa64c8c72009-07-20 15:07:26 -0700149 size_t size = num * sizeof(Metadata::Type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700150
Nicolas Catania48290382009-07-10 13:53:06 -0700151
152 if (p.dataAvail() < size)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700153 {
Andy Hung833b4752016-04-04 17:15:48 -0700154 ALOGE("Filter too short expected %zu but got %zu", size, p.dataAvail());
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700155 *status = NOT_ENOUGH_DATA;
156 return false;
157 }
158
nikoa64c8c72009-07-20 15:07:26 -0700159 const Metadata::Type *data =
160 static_cast<const Metadata::Type*>(p.readInplace(size));
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700161
Nicolas Catania48290382009-07-10 13:53:06 -0700162 if (NULL == data)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700163 {
Steve Block29357bc2012-01-06 19:20:56 +0000164 ALOGE("Filter had no data");
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700165 *status = BAD_VALUE;
166 return false;
167 }
168
169 // TODO: The stl impl of vector would be more efficient here
170 // because it degenerates into a memcpy on pod types. Try to
171 // replace later or use stl::set.
Nicolas Catania48290382009-07-10 13:53:06 -0700172 for (size_t i = 0; i < num; ++i)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700173 {
Nicolas Catania48290382009-07-10 13:53:06 -0700174 filter->add(*data);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700175 ++data;
176 }
177 *status = OK;
178 return true;
179}
180
Nicolas Catania48290382009-07-10 13:53:06 -0700181// @param filter Of metadata type.
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700182// @param val To be searched.
183// @return true if a match was found.
nikoa64c8c72009-07-20 15:07:26 -0700184bool findMetadata(const Metadata::Filter& filter, const int32_t val)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700185{
186 // Deal with empty and ANY right away
187 if (filter.isEmpty()) return false;
nikoa64c8c72009-07-20 15:07:26 -0700188 if (filter[0] == Metadata::kAny) return true;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700189
Nicolas Catania48290382009-07-10 13:53:06 -0700190 return filter.indexOf(val) >= 0;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700191}
192
193} // anonymous namespace
194
195
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700196namespace {
197using android::Parcel;
198using android::String16;
199
200// marshalling tag indicating flattened utf16 tags
201// keep in sync with frameworks/base/media/java/android/media/AudioAttributes.java
202const int32_t kAudioAttributesMarshallTagFlattenTags = 1;
203
204// Audio attributes format in a parcel:
205//
206// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
207// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
208// | usage |
209// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
210// | content_type |
211// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Hyejin Kim4f418f92014-09-05 15:50:03 +0900212// | source |
213// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700214// | flags |
215// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
216// | kAudioAttributesMarshallTagFlattenTags | // ignore tags if not found
217// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
218// | flattened tags in UTF16 |
219// | ... |
220// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
221//
222// @param p Parcel that contains audio attributes.
223// @param[out] attributes On exit points to an initialized audio_attributes_t structure
224// @param[out] status On exit contains the status code to be returned.
225void unmarshallAudioAttributes(const Parcel& parcel, audio_attributes_t *attributes)
226{
227 attributes->usage = (audio_usage_t) parcel.readInt32();
228 attributes->content_type = (audio_content_type_t) parcel.readInt32();
Hyejin Kim4f418f92014-09-05 15:50:03 +0900229 attributes->source = (audio_source_t) parcel.readInt32();
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700230 attributes->flags = (audio_flags_mask_t) parcel.readInt32();
231 const bool hasFlattenedTag = (parcel.readInt32() == kAudioAttributesMarshallTagFlattenTags);
232 if (hasFlattenedTag) {
233 // the tags are UTF16, convert to UTF8
234 String16 tags = parcel.readString16();
235 ssize_t realTagSize = utf16_to_utf8_length(tags.string(), tags.size());
236 if (realTagSize <= 0) {
237 strcpy(attributes->tags, "");
238 } else {
239 // copy the flattened string into the attributes as the destination for the conversion:
240 // copying array size -1, array for tags was calloc'd, no need to NULL-terminate it
241 size_t tagSize = realTagSize > AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 ?
242 AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 : realTagSize;
Sergio Giro1d3f4272016-06-28 18:24:52 +0100243 utf16_to_utf8(tags.string(), tagSize, attributes->tags,
244 sizeof(attributes->tags) / sizeof(attributes->tags[0]));
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700245 }
246 } else {
247 ALOGE("unmarshallAudioAttributes() received unflattened tags, ignoring tag values");
248 strcpy(attributes->tags, "");
249 }
250}
251} // anonymous namespace
252
253
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800254namespace android {
255
Marco Nelissenf09611f2015-02-13 14:12:42 -0800256extern ALooperRoster gLooperRoster;
257
258
Dave Burked681bbb2011-08-30 14:39:17 +0100259static bool checkPermission(const char* permissionString) {
Dave Burked681bbb2011-08-30 14:39:17 +0100260 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
261 bool ok = checkCallingPermission(String16(permissionString));
Steve Block29357bc2012-01-06 19:20:56 +0000262 if (!ok) ALOGE("Request requires %s", permissionString);
Dave Burked681bbb2011-08-30 14:39:17 +0100263 return ok;
264}
265
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800266// 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 -0800267/* static */ int MediaPlayerService::AudioOutput::mMinBufferCount = 4;
268/* static */ bool MediaPlayerService::AudioOutput::mIsOnEmulator = false;
269
270void MediaPlayerService::instantiate() {
271 defaultServiceManager()->addService(
272 String16("media.player"), new MediaPlayerService());
273}
274
275MediaPlayerService::MediaPlayerService()
276{
Steve Block3856b092011-10-20 11:56:00 +0100277 ALOGV("MediaPlayerService created");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800278 mNextConnId = 1;
Gloria Wang9ee159b2011-02-24 14:51:45 -0800279
280 mBatteryAudio.refCount = 0;
281 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
282 mBatteryAudio.deviceOn[i] = 0;
283 mBatteryAudio.lastTime[i] = 0;
284 mBatteryAudio.totalTime[i] = 0;
285 }
286 // speaker is on by default
287 mBatteryAudio.deviceOn[SPEAKER] = 1;
John Grossman44a7e422012-06-21 17:29:24 -0700288
Chong Zhang0b30fd42014-07-23 14:46:05 -0700289 // reset battery stats
290 // if the mediaserver has crashed, battery stats could be left
291 // in bad state, reset the state upon service start.
Wei Jia3f273d12015-11-24 09:06:49 -0800292 BatteryNotifier::getInstance().noteResetVideo();
Chong Zhang0b30fd42014-07-23 14:46:05 -0700293
John Grossman44a7e422012-06-21 17:29:24 -0700294 MediaPlayerFactory::registerBuiltinFactories();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800295}
296
297MediaPlayerService::~MediaPlayerService()
298{
Steve Block3856b092011-10-20 11:56:00 +0100299 ALOGV("MediaPlayerService destroyed");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800300}
301
Svet Ganovbe71aa22015-04-28 12:06:02 -0700302sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(const String16 &opPackageName)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800303{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800304 pid_t pid = IPCThreadState::self()->getCallingPid();
Svet Ganovbe71aa22015-04-28 12:06:02 -0700305 sp<MediaRecorderClient> recorder = new MediaRecorderClient(this, pid, opPackageName);
Gloria Wangdac6a312009-10-29 15:46:37 -0700306 wp<MediaRecorderClient> w = recorder;
307 Mutex::Autolock lock(mLock);
308 mMediaRecorderClients.add(w);
Steve Block3856b092011-10-20 11:56:00 +0100309 ALOGV("Create new media recorder client from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800310 return recorder;
311}
312
Gloria Wangdac6a312009-10-29 15:46:37 -0700313void MediaPlayerService::removeMediaRecorderClient(wp<MediaRecorderClient> client)
314{
315 Mutex::Autolock lock(mLock);
316 mMediaRecorderClients.remove(client);
Steve Block3856b092011-10-20 11:56:00 +0100317 ALOGV("Delete media recorder client");
Gloria Wangdac6a312009-10-29 15:46:37 -0700318}
319
Glenn Kastenf37971f2012-02-03 11:06:53 -0800320sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800321{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800322 pid_t pid = IPCThreadState::self()->getCallingPid();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800323 sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
Steve Block3856b092011-10-20 11:56:00 +0100324 ALOGV("Create new media retriever from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800325 return retriever;
326}
327
Glenn Kastenf37971f2012-02-03 11:06:53 -0800328sp<IMediaPlayer> MediaPlayerService::create(const sp<IMediaPlayerClient>& client,
Glenn Kastend848eb42016-03-08 13:42:11 -0800329 audio_session_t audioSessionId)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800330{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800331 pid_t pid = IPCThreadState::self()->getCallingPid();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800332 int32_t connId = android_atomic_inc(&mNextConnId);
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700333
334 sp<Client> c = new Client(
335 this, pid, connId, client, audioSessionId,
336 IPCThreadState::self()->getCallingUid());
337
Steve Block3856b092011-10-20 11:56:00 +0100338 ALOGV("Create new client(%d) from pid %d, uid %d, ", connId, pid,
Dave Burked681bbb2011-08-30 14:39:17 +0100339 IPCThreadState::self()->getCallingUid());
340
341 wp<Client> w = c;
342 {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800343 Mutex::Autolock lock(mLock);
344 mClients.add(w);
345 }
Andreas Hubere2b10282010-11-23 11:41:34 -0800346 return c;
347}
348
Lajos Molnar1381d4b2014-08-07 15:18:35 -0700349sp<IMediaCodecList> MediaPlayerService::getCodecList() const {
350 return MediaCodecList::getLocalInstance();
351}
352
Marco Nelissen260e56c2016-01-28 21:41:25 +0000353sp<IOMX> MediaPlayerService::getOMX() {
Marco Nelissen1900e772016-02-02 16:12:16 -0800354 ALOGI("MediaPlayerService::getOMX");
Marco Nelissen260e56c2016-01-28 21:41:25 +0000355 Mutex::Autolock autoLock(mLock);
356
357 if (mOMX.get() == NULL) {
358 mOMX = new OMX;
359 }
360
361 return mOMX;
362}
363
Andreas Huber279dcd82013-01-30 10:41:25 -0800364sp<IHDCP> MediaPlayerService::makeHDCP(bool createEncryptionModule) {
365 return new HDCP(createEncryptionModule);
Andreas Huber59451f82012-09-18 10:36:32 -0700366}
367
Jeff Brown2013a542012-09-04 21:38:42 -0700368sp<IRemoteDisplay> MediaPlayerService::listenForRemoteDisplay(
Svet Ganovbe71aa22015-04-28 12:06:02 -0700369 const String16 &opPackageName,
Jeff Brown2013a542012-09-04 21:38:42 -0700370 const sp<IRemoteDisplayClient>& client, const String8& iface) {
Jeff Brownaba33d52012-09-07 17:38:58 -0700371 if (!checkPermission("android.permission.CONTROL_WIFI_DISPLAY")) {
372 return NULL;
373 }
374
Svet Ganovbe71aa22015-04-28 12:06:02 -0700375 return new RemoteDisplay(opPackageName, client, iface.string());
Jeff Brown2013a542012-09-04 21:38:42 -0700376}
377
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800378status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
379{
380 const size_t SIZE = 256;
381 char buffer[SIZE];
382 String8 result;
383
384 result.append(" AudioOutput\n");
385 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n",
386 mStreamType, mLeftVolume, mRightVolume);
387 result.append(buffer);
388 snprintf(buffer, 255, " msec per frame(%f), latency (%d)\n",
Eric Laurentdb354e52012-03-05 17:27:11 -0800389 mMsecsPerFrame, (mTrack != 0) ? mTrack->latency() : -1);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800390 result.append(buffer);
Eric Laurent2beeb502010-07-16 07:43:46 -0700391 snprintf(buffer, 255, " aux effect id(%d), send level (%f)\n",
392 mAuxEffectId, mSendLevel);
393 result.append(buffer);
394
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800395 ::write(fd, result.string(), result.size());
396 if (mTrack != 0) {
397 mTrack->dump(fd, args);
398 }
399 return NO_ERROR;
400}
401
Lajos Molnar6d339f12015-04-17 16:15:53 -0700402status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800403{
404 const size_t SIZE = 256;
405 char buffer[SIZE];
406 String8 result;
407 result.append(" Client\n");
408 snprintf(buffer, 255, " pid(%d), connId(%d), status(%d), looping(%s)\n",
409 mPid, mConnId, mStatus, mLoop?"true": "false");
410 result.append(buffer);
Wei Jia502c2f42017-07-13 17:47:56 -0700411
412 sp<MediaPlayerBase> p;
413 sp<AudioOutput> audioOutput;
414 bool locked = false;
415 for (int i = 0; i < kDumpLockRetries; ++i) {
416 if (mLock.tryLock() == NO_ERROR) {
417 locked = true;
418 break;
419 }
420 usleep(kDumpLockSleepUs);
Andreas Hubera0b1d4b2011-06-07 15:52:25 -0700421 }
Wei Jia502c2f42017-07-13 17:47:56 -0700422
423 if (locked) {
424 p = mPlayer;
425 audioOutput = mAudioOutput;
426 mLock.unlock();
427 } else {
428 result.append(" lock is taken, no dump from player and audio output\n");
429 }
430 write(fd, result.string(), result.size());
431
432 if (p != NULL) {
433 p->dump(fd, args);
434 }
435 if (audioOutput != 0) {
436 audioOutput->dump(fd, args);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800437 }
438 write(fd, "\n", 1);
439 return NO_ERROR;
440}
441
Marco Nelissenf09611f2015-02-13 14:12:42 -0800442/**
443 * The only arguments this understands right now are -c, -von and -voff,
444 * which are parsed by ALooperRoster::dump()
445 */
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800446status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
447{
448 const size_t SIZE = 256;
449 char buffer[SIZE];
450 String8 result;
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530451 SortedVector< sp<Client> > clients; //to serialise the mutex unlock & client destruction.
452 SortedVector< sp<MediaRecorderClient> > mediaRecorderClients;
453
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800454 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
455 snprintf(buffer, SIZE, "Permission Denial: "
456 "can't dump MediaPlayerService from pid=%d, uid=%d\n",
457 IPCThreadState::self()->getCallingPid(),
458 IPCThreadState::self()->getCallingUid());
459 result.append(buffer);
460 } else {
461 Mutex::Autolock lock(mLock);
462 for (int i = 0, n = mClients.size(); i < n; ++i) {
463 sp<Client> c = mClients[i].promote();
464 if (c != 0) c->dump(fd, args);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530465 clients.add(c);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800466 }
James Dongb9141222010-07-08 11:16:11 -0700467 if (mMediaRecorderClients.size() == 0) {
468 result.append(" No media recorder client\n\n");
469 } else {
470 for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
471 sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
James Donge579e282011-10-18 22:29:20 -0700472 if (c != 0) {
473 snprintf(buffer, 255, " MediaRecorderClient pid(%d)\n", c->mPid);
474 result.append(buffer);
475 write(fd, result.string(), result.size());
476 result = "\n";
477 c->dump(fd, args);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530478 mediaRecorderClients.add(c);
James Donge579e282011-10-18 22:29:20 -0700479 }
James Dongb9141222010-07-08 11:16:11 -0700480 }
Gloria Wangdac6a312009-10-29 15:46:37 -0700481 }
482
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800483 result.append(" Files opened and/or mapped:\n");
Marco Nelissenf09611f2015-02-13 14:12:42 -0800484 snprintf(buffer, SIZE, "/proc/%d/maps", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800485 FILE *f = fopen(buffer, "r");
486 if (f) {
487 while (!feof(f)) {
488 fgets(buffer, SIZE, f);
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700489 if (strstr(buffer, " /storage/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800490 strstr(buffer, " /system/sounds/") ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700491 strstr(buffer, " /data/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800492 strstr(buffer, " /system/media/")) {
493 result.append(" ");
494 result.append(buffer);
495 }
496 }
497 fclose(f);
498 } else {
499 result.append("couldn't open ");
500 result.append(buffer);
501 result.append("\n");
502 }
503
Marco Nelissenf09611f2015-02-13 14:12:42 -0800504 snprintf(buffer, SIZE, "/proc/%d/fd", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800505 DIR *d = opendir(buffer);
506 if (d) {
507 struct dirent *ent;
508 while((ent = readdir(d)) != NULL) {
509 if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
Marco Nelissenf09611f2015-02-13 14:12:42 -0800510 snprintf(buffer, SIZE, "/proc/%d/fd/%s", getpid(), ent->d_name);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800511 struct stat s;
512 if (lstat(buffer, &s) == 0) {
513 if ((s.st_mode & S_IFMT) == S_IFLNK) {
514 char linkto[256];
515 int len = readlink(buffer, linkto, sizeof(linkto));
516 if(len > 0) {
517 if(len > 255) {
518 linkto[252] = '.';
519 linkto[253] = '.';
520 linkto[254] = '.';
521 linkto[255] = 0;
522 } else {
523 linkto[len] = 0;
524 }
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700525 if (strstr(linkto, "/storage/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800526 strstr(linkto, "/system/sounds/") == linkto ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700527 strstr(linkto, "/data/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800528 strstr(linkto, "/system/media/") == linkto) {
529 result.append(" ");
530 result.append(buffer);
531 result.append(" -> ");
532 result.append(linkto);
533 result.append("\n");
534 }
535 }
536 } else {
537 result.append(" unexpected type for ");
538 result.append(buffer);
539 result.append("\n");
540 }
541 }
542 }
543 }
544 closedir(d);
545 } else {
546 result.append("couldn't open ");
547 result.append(buffer);
548 result.append("\n");
549 }
550
Marco Nelissenf09611f2015-02-13 14:12:42 -0800551 gLooperRoster.dump(fd, args);
552
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800553 bool dumpMem = false;
Andy Hung53541292016-04-13 16:48:51 -0700554 bool unreachableMemory = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800555 for (size_t i = 0; i < args.size(); i++) {
556 if (args[i] == String16("-m")) {
557 dumpMem = true;
Andy Hung53541292016-04-13 16:48:51 -0700558 } else if (args[i] == String16("--unreachable")) {
559 unreachableMemory = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800560 }
561 }
562 if (dumpMem) {
Andy Hung07b745e2016-05-23 16:21:07 -0700563 result.append("\nDumping memory:\n");
564 std::string s = dumpMemoryAddresses(100 /* limit */);
565 result.append(s.c_str(), s.size());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800566 }
Andy Hung53541292016-04-13 16:48:51 -0700567 if (unreachableMemory) {
568 result.append("\nDumping unreachable memory:\n");
569 // TODO - should limit be an argument parameter?
570 std::string s = GetUnreachableMemoryString(true /* contents */, 10000 /* limit */);
571 result.append(s.c_str(), s.size());
572 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800573 }
574 write(fd, result.string(), result.size());
575 return NO_ERROR;
576}
577
578void MediaPlayerService::removeClient(wp<Client> client)
579{
580 Mutex::Autolock lock(mLock);
581 mClients.remove(client);
582}
583
Robert Shihee0a0e32016-08-16 16:50:54 -0700584bool MediaPlayerService::hasClient(wp<Client> client)
585{
586 Mutex::Autolock lock(mLock);
587 return mClients.indexOf(client) != NAME_NOT_FOUND;
588}
589
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700590MediaPlayerService::Client::Client(
591 const sp<MediaPlayerService>& service, pid_t pid,
592 int32_t connId, const sp<IMediaPlayerClient>& client,
Glenn Kastend848eb42016-03-08 13:42:11 -0800593 audio_session_t audioSessionId, uid_t uid)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800594{
Steve Block3856b092011-10-20 11:56:00 +0100595 ALOGV("Client(%d) constructor", connId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800596 mPid = pid;
597 mConnId = connId;
598 mService = service;
599 mClient = client;
600 mLoop = false;
601 mStatus = NO_INIT;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700602 mAudioSessionId = audioSessionId;
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700603 mUID = uid;
John Grossmanc795b642012-02-22 15:38:35 -0800604 mRetransmitEndpointValid = false;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700605 mAudioAttributes = NULL;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700606
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800607#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000608 ALOGD("create Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800609 mAntagonizer = new Antagonizer(notify, this);
610#endif
611}
612
613MediaPlayerService::Client::~Client()
614{
Steve Block3856b092011-10-20 11:56:00 +0100615 ALOGV("Client(%d) destructor pid = %d", mConnId, mPid);
Wei Jia502c2f42017-07-13 17:47:56 -0700616 {
617 Mutex::Autolock l(mLock);
618 mAudioOutput.clear();
619 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800620 wp<Client> client(this);
621 disconnect();
622 mService->removeClient(client);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700623 if (mAudioAttributes != NULL) {
624 free(mAudioAttributes);
625 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800626}
627
628void MediaPlayerService::Client::disconnect()
629{
Steve Block3856b092011-10-20 11:56:00 +0100630 ALOGV("disconnect(%d) from pid %d", mConnId, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800631 // grab local reference and clear main reference to prevent future
632 // access to object
633 sp<MediaPlayerBase> p;
634 {
635 Mutex::Autolock l(mLock);
636 p = mPlayer;
beanzdcfefde2012-11-05 09:51:43 +0800637 mClient.clear();
Wei Jia502c2f42017-07-13 17:47:56 -0700638 mPlayer.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800639 }
Andreas Huber20111aa2009-07-14 16:56:47 -0700640
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800641 // clear the notification to prevent callbacks to dead client
642 // and reset the player. We assume the player will serialize
643 // access to itself if necessary.
644 if (p != 0) {
645 p->setNotifyCallback(0, 0);
646#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000647 ALOGD("kill Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800648 mAntagonizer->kill();
649#endif
650 p->reset();
651 }
652
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700653 disconnectNativeWindow();
654
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800655 IPCThreadState::self()->flushCommands();
656}
657
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800658sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
659{
660 // determine if we have the right player type
Wei Jia502c2f42017-07-13 17:47:56 -0700661 sp<MediaPlayerBase> p = getPlayer();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800662 if ((p != NULL) && (p->playerType() != playerType)) {
Steve Block3856b092011-10-20 11:56:00 +0100663 ALOGV("delete player");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800664 p.clear();
665 }
666 if (p == NULL) {
Ronghua Wu68845c12015-07-21 09:50:48 -0700667 p = MediaPlayerFactory::createPlayer(playerType, this, notify, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800668 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700669
Jason Simmonsdb29e522011-08-12 13:46:55 -0700670 if (p != NULL) {
671 p->setUID(mUID);
672 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700673
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800674 return p;
675}
676
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700677MediaPlayerService::Client::ServiceDeathNotifier::ServiceDeathNotifier(
678 const sp<IBinder>& service,
679 const sp<MediaPlayerBase>& listener,
680 int which) {
681 mService = service;
682 mListener = listener;
683 mWhich = which;
684}
685
686MediaPlayerService::Client::ServiceDeathNotifier::~ServiceDeathNotifier() {
687 mService->unlinkToDeath(this);
688}
689
690void MediaPlayerService::Client::ServiceDeathNotifier::binderDied(const wp<IBinder>& /*who*/) {
691 sp<MediaPlayerBase> listener = mListener.promote();
692 if (listener != NULL) {
693 listener->sendEvent(MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED, mWhich);
694 } else {
695 ALOGW("listener for process %d death is gone", mWhich);
696 }
697}
698
John Grossmanc795b642012-02-22 15:38:35 -0800699sp<MediaPlayerBase> MediaPlayerService::Client::setDataSource_pre(
700 player_type playerType)
701{
702 ALOGV("player type = %d", playerType);
703
704 // create the right type of player
705 sp<MediaPlayerBase> p = createPlayer(playerType);
706 if (p == NULL) {
707 return p;
708 }
709
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700710 sp<IServiceManager> sm = defaultServiceManager();
711 sp<IBinder> binder = sm->getService(String16("media.extractor"));
712 mExtractorDeathListener = new ServiceDeathNotifier(binder, p, MEDIAEXTRACTOR_PROCESS_DEATH);
713 binder->linkToDeath(mExtractorDeathListener);
714
715 binder = sm->getService(String16("media.codec"));
716 mCodecDeathListener = new ServiceDeathNotifier(binder, p, MEDIACODEC_PROCESS_DEATH);
717 binder->linkToDeath(mCodecDeathListener);
718
John Grossmanc795b642012-02-22 15:38:35 -0800719 if (!p->hardwareOutput()) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -0700720 Mutex::Autolock l(mLock);
Marco Nelissend457c972014-02-11 08:47:07 -0800721 mAudioOutput = new AudioOutput(mAudioSessionId, IPCThreadState::self()->getCallingUid(),
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700722 mPid, mAudioAttributes);
John Grossmanc795b642012-02-22 15:38:35 -0800723 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
724 }
725
726 return p;
727}
728
729void MediaPlayerService::Client::setDataSource_post(
730 const sp<MediaPlayerBase>& p,
731 status_t status)
732{
733 ALOGV(" setDataSource");
734 mStatus = status;
735 if (mStatus != OK) {
736 ALOGE(" error: %d", mStatus);
737 return;
738 }
739
740 // Set the re-transmission endpoint if one was chosen.
741 if (mRetransmitEndpointValid) {
742 mStatus = p->setRetransmitEndpoint(&mRetransmitEndpoint);
743 if (mStatus != NO_ERROR) {
744 ALOGE("setRetransmitEndpoint error: %d", mStatus);
745 }
746 }
747
748 if (mStatus == OK) {
Wei Jia502c2f42017-07-13 17:47:56 -0700749 Mutex::Autolock l(mLock);
John Grossmanc795b642012-02-22 15:38:35 -0800750 mPlayer = p;
751 }
752}
753
Andreas Huber2db84552010-01-28 11:19:57 -0800754status_t MediaPlayerService::Client::setDataSource(
Andreas Huber1b86fe02014-01-29 11:13:26 -0800755 const sp<IMediaHTTPService> &httpService,
756 const char *url,
757 const KeyedVector<String8, String8> *headers)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800758{
Steve Block3856b092011-10-20 11:56:00 +0100759 ALOGV("setDataSource(%s)", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800760 if (url == NULL)
761 return UNKNOWN_ERROR;
762
Dave Burked681bbb2011-08-30 14:39:17 +0100763 if ((strncmp(url, "http://", 7) == 0) ||
764 (strncmp(url, "https://", 8) == 0) ||
765 (strncmp(url, "rtsp://", 7) == 0)) {
766 if (!checkPermission("android.permission.INTERNET")) {
767 return PERMISSION_DENIED;
768 }
769 }
770
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800771 if (strncmp(url, "content://", 10) == 0) {
772 // get a filedescriptor for the content Uri and
773 // pass it to the setDataSource(fd) method
774
775 String16 url16(url);
776 int fd = android::openContentProviderFile(url16);
777 if (fd < 0)
778 {
Steve Block29357bc2012-01-06 19:20:56 +0000779 ALOGE("Couldn't open fd for %s", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800780 return UNKNOWN_ERROR;
781 }
782 setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
783 close(fd);
784 return mStatus;
785 } else {
John Grossman44a7e422012-06-21 17:29:24 -0700786 player_type playerType = MediaPlayerFactory::getPlayerType(this, url);
John Grossmanc795b642012-02-22 15:38:35 -0800787 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
788 if (p == NULL) {
789 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800790 }
791
Andreas Huber1b86fe02014-01-29 11:13:26 -0800792 setDataSource_post(p, p->setDataSource(httpService, url, headers));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800793 return mStatus;
794 }
795}
796
797status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
798{
Marco Nelissen83b0fd92015-09-16 13:48:07 -0700799 ALOGV("setDataSource fd=%d (%s), offset=%lld, length=%lld",
800 fd, nameForFd(fd).c_str(), (long long) offset, (long long) length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800801 struct stat sb;
802 int ret = fstat(fd, &sb);
803 if (ret != 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000804 ALOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800805 return UNKNOWN_ERROR;
806 }
807
Andy Hung833b4752016-04-04 17:15:48 -0700808 ALOGV("st_dev = %llu", static_cast<unsigned long long>(sb.st_dev));
Steve Block3856b092011-10-20 11:56:00 +0100809 ALOGV("st_mode = %u", sb.st_mode);
Mark Salyzyn77342f72014-06-18 16:31:32 -0700810 ALOGV("st_uid = %lu", static_cast<unsigned long>(sb.st_uid));
811 ALOGV("st_gid = %lu", static_cast<unsigned long>(sb.st_gid));
Andy Hung833b4752016-04-04 17:15:48 -0700812 ALOGV("st_size = %llu", static_cast<unsigned long long>(sb.st_size));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800813
814 if (offset >= sb.st_size) {
Steve Block29357bc2012-01-06 19:20:56 +0000815 ALOGE("offset error");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800816 return UNKNOWN_ERROR;
817 }
818 if (offset + length > sb.st_size) {
819 length = sb.st_size - offset;
Andy Hung833b4752016-04-04 17:15:48 -0700820 ALOGV("calculated length = %lld", (long long)length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800821 }
822
John Grossman44a7e422012-06-21 17:29:24 -0700823 player_type playerType = MediaPlayerFactory::getPlayerType(this,
824 fd,
825 offset,
826 length);
John Grossmanc795b642012-02-22 15:38:35 -0800827 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
828 if (p == NULL) {
829 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800830 }
831
832 // now set data source
John Grossmanc795b642012-02-22 15:38:35 -0800833 setDataSource_post(p, p->setDataSource(fd, offset, length));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800834 return mStatus;
835}
836
Andreas Hubere2b10282010-11-23 11:41:34 -0800837status_t MediaPlayerService::Client::setDataSource(
838 const sp<IStreamSource> &source) {
839 // create the right type of player
John Grossman44a7e422012-06-21 17:29:24 -0700840 player_type playerType = MediaPlayerFactory::getPlayerType(this, source);
John Grossmanc795b642012-02-22 15:38:35 -0800841 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
Andreas Hubere2b10282010-11-23 11:41:34 -0800842 if (p == NULL) {
843 return NO_INIT;
844 }
845
Andreas Hubere2b10282010-11-23 11:41:34 -0800846 // now set data source
John Grossmanc795b642012-02-22 15:38:35 -0800847 setDataSource_post(p, p->setDataSource(source));
Andreas Hubere2b10282010-11-23 11:41:34 -0800848 return mStatus;
849}
850
Chris Watkins99f31602015-03-20 13:06:33 -0700851status_t MediaPlayerService::Client::setDataSource(
852 const sp<IDataSource> &source) {
853 sp<DataSource> dataSource = DataSource::CreateFromIDataSource(source);
854 player_type playerType = MediaPlayerFactory::getPlayerType(this, dataSource);
855 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
856 if (p == NULL) {
857 return NO_INIT;
858 }
859 // now set data source
860 setDataSource_post(p, p->setDataSource(dataSource));
861 return mStatus;
862}
863
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700864void MediaPlayerService::Client::disconnectNativeWindow() {
865 if (mConnectedWindow != NULL) {
866 status_t err = native_window_api_disconnect(mConnectedWindow.get(),
867 NATIVE_WINDOW_API_MEDIA);
868
869 if (err != OK) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000870 ALOGW("native_window_api_disconnect returned an error: %s (%d)",
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700871 strerror(-err), err);
872 }
873 }
874 mConnectedWindow.clear();
875}
876
Glenn Kasten11731182011-02-08 17:26:17 -0800877status_t MediaPlayerService::Client::setVideoSurfaceTexture(
Andy McFadden484566c2012-12-18 09:46:54 -0800878 const sp<IGraphicBufferProducer>& bufferProducer)
Glenn Kasten11731182011-02-08 17:26:17 -0800879{
Andy McFadden484566c2012-12-18 09:46:54 -0800880 ALOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, bufferProducer.get());
Glenn Kasten11731182011-02-08 17:26:17 -0800881 sp<MediaPlayerBase> p = getPlayer();
882 if (p == 0) return UNKNOWN_ERROR;
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700883
Marco Nelissenf8880202014-11-14 07:58:25 -0800884 sp<IBinder> binder(IInterface::asBinder(bufferProducer));
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700885 if (mConnectedWindowBinder == binder) {
886 return OK;
887 }
888
889 sp<ANativeWindow> anw;
Andy McFadden484566c2012-12-18 09:46:54 -0800890 if (bufferProducer != NULL) {
Marco Nelissenee08f7e2013-09-16 13:30:01 -0700891 anw = new Surface(bufferProducer, true /* controlledByApp */);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700892 status_t err = native_window_api_connect(anw.get(),
893 NATIVE_WINDOW_API_MEDIA);
894
895 if (err != OK) {
Steve Block29357bc2012-01-06 19:20:56 +0000896 ALOGE("setVideoSurfaceTexture failed: %d", err);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700897 // Note that we must do the reset before disconnecting from the ANW.
898 // Otherwise queue/dequeue calls could be made on the disconnected
899 // ANW, which may result in errors.
900 reset();
901
902 disconnectNativeWindow();
903
904 return err;
905 }
906 }
907
Andy McFadden484566c2012-12-18 09:46:54 -0800908 // Note that we must set the player's new GraphicBufferProducer before
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700909 // disconnecting the old one. Otherwise queue/dequeue calls could be made
910 // on the disconnected ANW, which may result in errors.
Andy McFadden484566c2012-12-18 09:46:54 -0800911 status_t err = p->setVideoSurfaceTexture(bufferProducer);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700912
913 disconnectNativeWindow();
914
915 mConnectedWindow = anw;
916
917 if (err == OK) {
918 mConnectedWindowBinder = binder;
919 } else {
920 disconnectNativeWindow();
921 }
922
923 return err;
Glenn Kasten11731182011-02-08 17:26:17 -0800924}
925
Nicolas Catania1d187f12009-05-12 23:25:55 -0700926status_t MediaPlayerService::Client::invoke(const Parcel& request,
927 Parcel *reply)
928{
929 sp<MediaPlayerBase> p = getPlayer();
930 if (p == NULL) return UNKNOWN_ERROR;
931 return p->invoke(request, reply);
932}
933
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700934// This call doesn't need to access the native player.
935status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
936{
937 status_t status;
nikoa64c8c72009-07-20 15:07:26 -0700938 media::Metadata::Filter allow, drop;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700939
Nicolas Catania48290382009-07-10 13:53:06 -0700940 if (unmarshallFilter(filter, &allow, &status) &&
941 unmarshallFilter(filter, &drop, &status)) {
942 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700943
944 mMetadataAllow = allow;
945 mMetadataDrop = drop;
946 }
947 return status;
948}
949
Nicolas Catania48290382009-07-10 13:53:06 -0700950status_t MediaPlayerService::Client::getMetadata(
Mark Salyzyn77342f72014-06-18 16:31:32 -0700951 bool update_only, bool /*apply_filter*/, Parcel *reply)
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700952{
nikoa64c8c72009-07-20 15:07:26 -0700953 sp<MediaPlayerBase> player = getPlayer();
954 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania48290382009-07-10 13:53:06 -0700955
nikod608a812009-07-16 16:39:53 -0700956 status_t status;
957 // Placeholder for the return code, updated by the caller.
958 reply->writeInt32(-1);
959
nikoa64c8c72009-07-20 15:07:26 -0700960 media::Metadata::Filter ids;
Nicolas Catania48290382009-07-10 13:53:06 -0700961
962 // We don't block notifications while we fetch the data. We clear
963 // mMetadataUpdated first so we don't lose notifications happening
964 // during the rest of this call.
965 {
966 Mutex::Autolock lock(mLock);
967 if (update_only) {
nikod608a812009-07-16 16:39:53 -0700968 ids = mMetadataUpdated;
Nicolas Catania48290382009-07-10 13:53:06 -0700969 }
970 mMetadataUpdated.clear();
971 }
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700972
nikoa64c8c72009-07-20 15:07:26 -0700973 media::Metadata metadata(reply);
Nicolas Catania48290382009-07-10 13:53:06 -0700974
nikoa64c8c72009-07-20 15:07:26 -0700975 metadata.appendHeader();
976 status = player->getMetadata(ids, reply);
nikod608a812009-07-16 16:39:53 -0700977
978 if (status != OK) {
nikoa64c8c72009-07-20 15:07:26 -0700979 metadata.resetParcel();
Steve Block29357bc2012-01-06 19:20:56 +0000980 ALOGE("getMetadata failed %d", status);
nikod608a812009-07-16 16:39:53 -0700981 return status;
982 }
983
984 // FIXME: Implement filtering on the result. Not critical since
985 // filtering takes place on the update notifications already. This
986 // would be when all the metadata are fetch and a filter is set.
987
nikod608a812009-07-16 16:39:53 -0700988 // Everything is fine, update the metadata length.
nikoa64c8c72009-07-20 15:07:26 -0700989 metadata.updateLength();
nikod608a812009-07-16 16:39:53 -0700990 return OK;
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700991}
992
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800993status_t MediaPlayerService::Client::prepareAsync()
994{
Steve Block3856b092011-10-20 11:56:00 +0100995 ALOGV("[%d] prepareAsync", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800996 sp<MediaPlayerBase> p = getPlayer();
997 if (p == 0) return UNKNOWN_ERROR;
998 status_t ret = p->prepareAsync();
999#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +00001000 ALOGD("start Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001001 if (ret == NO_ERROR) mAntagonizer->start();
1002#endif
1003 return ret;
1004}
1005
1006status_t MediaPlayerService::Client::start()
1007{
Steve Block3856b092011-10-20 11:56:00 +01001008 ALOGV("[%d] start", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001009 sp<MediaPlayerBase> p = getPlayer();
1010 if (p == 0) return UNKNOWN_ERROR;
1011 p->setLooping(mLoop);
1012 return p->start();
1013}
1014
1015status_t MediaPlayerService::Client::stop()
1016{
Steve Block3856b092011-10-20 11:56:00 +01001017 ALOGV("[%d] stop", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001018 sp<MediaPlayerBase> p = getPlayer();
1019 if (p == 0) return UNKNOWN_ERROR;
1020 return p->stop();
1021}
1022
1023status_t MediaPlayerService::Client::pause()
1024{
Steve Block3856b092011-10-20 11:56:00 +01001025 ALOGV("[%d] pause", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001026 sp<MediaPlayerBase> p = getPlayer();
1027 if (p == 0) return UNKNOWN_ERROR;
1028 return p->pause();
1029}
1030
1031status_t MediaPlayerService::Client::isPlaying(bool* state)
1032{
1033 *state = false;
1034 sp<MediaPlayerBase> p = getPlayer();
1035 if (p == 0) return UNKNOWN_ERROR;
1036 *state = p->isPlaying();
Steve Block3856b092011-10-20 11:56:00 +01001037 ALOGV("[%d] isPlaying: %d", mConnId, *state);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001038 return NO_ERROR;
1039}
1040
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001041status_t MediaPlayerService::Client::setPlaybackSettings(const AudioPlaybackRate& rate)
Wei Jia98160162015-02-04 17:01:11 -08001042{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001043 ALOGV("[%d] setPlaybackSettings(%f, %f, %d, %d)",
1044 mConnId, rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Wei Jia98160162015-02-04 17:01:11 -08001045 sp<MediaPlayerBase> p = getPlayer();
1046 if (p == 0) return UNKNOWN_ERROR;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001047 return p->setPlaybackSettings(rate);
1048}
1049
1050status_t MediaPlayerService::Client::getPlaybackSettings(AudioPlaybackRate* rate /* nonnull */)
1051{
1052 sp<MediaPlayerBase> p = getPlayer();
1053 if (p == 0) return UNKNOWN_ERROR;
1054 status_t ret = p->getPlaybackSettings(rate);
1055 if (ret == NO_ERROR) {
1056 ALOGV("[%d] getPlaybackSettings(%f, %f, %d, %d)",
1057 mConnId, rate->mSpeed, rate->mPitch, rate->mFallbackMode, rate->mStretchMode);
1058 } else {
1059 ALOGV("[%d] getPlaybackSettings returned %d", mConnId, ret);
1060 }
1061 return ret;
1062}
1063
1064status_t MediaPlayerService::Client::setSyncSettings(
1065 const AVSyncSettings& sync, float videoFpsHint)
1066{
1067 ALOGV("[%d] setSyncSettings(%u, %u, %f, %f)",
1068 mConnId, sync.mSource, sync.mAudioAdjustMode, sync.mTolerance, videoFpsHint);
1069 sp<MediaPlayerBase> p = getPlayer();
1070 if (p == 0) return UNKNOWN_ERROR;
1071 return p->setSyncSettings(sync, videoFpsHint);
1072}
1073
1074status_t MediaPlayerService::Client::getSyncSettings(
1075 AVSyncSettings* sync /* nonnull */, float* videoFps /* nonnull */)
1076{
1077 sp<MediaPlayerBase> p = getPlayer();
1078 if (p == 0) return UNKNOWN_ERROR;
1079 status_t ret = p->getSyncSettings(sync, videoFps);
1080 if (ret == NO_ERROR) {
1081 ALOGV("[%d] getSyncSettings(%u, %u, %f, %f)",
1082 mConnId, sync->mSource, sync->mAudioAdjustMode, sync->mTolerance, *videoFps);
1083 } else {
1084 ALOGV("[%d] getSyncSettings returned %d", mConnId, ret);
1085 }
1086 return ret;
Wei Jia98160162015-02-04 17:01:11 -08001087}
1088
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001089status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
1090{
Steve Block3856b092011-10-20 11:56:00 +01001091 ALOGV("getCurrentPosition");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001092 sp<MediaPlayerBase> p = getPlayer();
1093 if (p == 0) return UNKNOWN_ERROR;
1094 status_t ret = p->getCurrentPosition(msec);
1095 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001096 ALOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001097 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001098 ALOGE("getCurrentPosition returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001099 }
1100 return ret;
1101}
1102
1103status_t MediaPlayerService::Client::getDuration(int *msec)
1104{
Steve Block3856b092011-10-20 11:56:00 +01001105 ALOGV("getDuration");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001106 sp<MediaPlayerBase> p = getPlayer();
1107 if (p == 0) return UNKNOWN_ERROR;
1108 status_t ret = p->getDuration(msec);
1109 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001110 ALOGV("[%d] getDuration = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001111 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001112 ALOGE("getDuration returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001113 }
1114 return ret;
1115}
1116
Marco Nelissen6b74d672012-02-28 16:07:44 -08001117status_t MediaPlayerService::Client::setNextPlayer(const sp<IMediaPlayer>& player) {
1118 ALOGV("setNextPlayer");
1119 Mutex::Autolock l(mLock);
1120 sp<Client> c = static_cast<Client*>(player.get());
Wei Jia28284122016-08-30 13:49:06 -07001121 if (c != NULL && !mService->hasClient(c)) {
Robert Shihee0a0e32016-08-16 16:50:54 -07001122 return BAD_VALUE;
1123 }
1124
Marco Nelissen6b74d672012-02-28 16:07:44 -08001125 mNextClient = c;
John Grossman5f7e55e2012-08-24 14:47:25 -07001126
1127 if (c != NULL) {
1128 if (mAudioOutput != NULL) {
1129 mAudioOutput->setNextOutput(c->mAudioOutput);
1130 } else if ((mPlayer != NULL) && !mPlayer->hardwareOutput()) {
1131 ALOGE("no current audio output");
1132 }
1133
1134 if ((mPlayer != NULL) && (mNextClient->getPlayer() != NULL)) {
1135 mPlayer->setNextPlayer(mNextClient->getPlayer());
1136 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001137 }
John Grossman5f7e55e2012-08-24 14:47:25 -07001138
Marco Nelissen6b74d672012-02-28 16:07:44 -08001139 return OK;
1140}
1141
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001142status_t MediaPlayerService::Client::seekTo(int msec)
1143{
Steve Block3856b092011-10-20 11:56:00 +01001144 ALOGV("[%d] seekTo(%d)", mConnId, msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001145 sp<MediaPlayerBase> p = getPlayer();
1146 if (p == 0) return UNKNOWN_ERROR;
1147 return p->seekTo(msec);
1148}
1149
1150status_t MediaPlayerService::Client::reset()
1151{
Steve Block3856b092011-10-20 11:56:00 +01001152 ALOGV("[%d] reset", mConnId);
John Grossmanc795b642012-02-22 15:38:35 -08001153 mRetransmitEndpointValid = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001154 sp<MediaPlayerBase> p = getPlayer();
1155 if (p == 0) return UNKNOWN_ERROR;
1156 return p->reset();
1157}
1158
Glenn Kastenfff6d712012-01-12 16:38:12 -08001159status_t MediaPlayerService::Client::setAudioStreamType(audio_stream_type_t type)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001160{
Steve Block3856b092011-10-20 11:56:00 +01001161 ALOGV("[%d] setAudioStreamType(%d)", mConnId, type);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001162 // TODO: for hardware output, call player instead
1163 Mutex::Autolock l(mLock);
1164 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1165 return NO_ERROR;
1166}
1167
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001168status_t MediaPlayerService::Client::setAudioAttributes_l(const Parcel &parcel)
1169{
1170 if (mAudioAttributes != NULL) { free(mAudioAttributes); }
1171 mAudioAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001172 if (mAudioAttributes == NULL) {
1173 return NO_MEMORY;
1174 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001175 unmarshallAudioAttributes(parcel, mAudioAttributes);
1176
1177 ALOGV("setAudioAttributes_l() usage=%d content=%d flags=0x%x tags=%s",
1178 mAudioAttributes->usage, mAudioAttributes->content_type, mAudioAttributes->flags,
1179 mAudioAttributes->tags);
1180
1181 if (mAudioOutput != 0) {
1182 mAudioOutput->setAudioAttributes(mAudioAttributes);
1183 }
1184 return NO_ERROR;
1185}
1186
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001187status_t MediaPlayerService::Client::setLooping(int loop)
1188{
Steve Block3856b092011-10-20 11:56:00 +01001189 ALOGV("[%d] setLooping(%d)", mConnId, loop);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001190 mLoop = loop;
1191 sp<MediaPlayerBase> p = getPlayer();
1192 if (p != 0) return p->setLooping(loop);
1193 return NO_ERROR;
1194}
1195
1196status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1197{
Steve Block3856b092011-10-20 11:56:00 +01001198 ALOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
John Grossman761defc2012-02-09 15:09:05 -08001199
1200 // for hardware output, call player instead
1201 sp<MediaPlayerBase> p = getPlayer();
1202 {
1203 Mutex::Autolock l(mLock);
1204 if (p != 0 && p->hardwareOutput()) {
1205 MediaPlayerHWInterface* hwp =
1206 reinterpret_cast<MediaPlayerHWInterface*>(p.get());
1207 return hwp->setVolume(leftVolume, rightVolume);
1208 } else {
1209 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1210 return NO_ERROR;
1211 }
1212 }
1213
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001214 return NO_ERROR;
1215}
1216
Eric Laurent2beeb502010-07-16 07:43:46 -07001217status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1218{
Steve Block3856b092011-10-20 11:56:00 +01001219 ALOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
Eric Laurent2beeb502010-07-16 07:43:46 -07001220 Mutex::Autolock l(mLock);
1221 if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1222 return NO_ERROR;
1223}
1224
1225status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1226{
Steve Block3856b092011-10-20 11:56:00 +01001227 ALOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
Eric Laurent2beeb502010-07-16 07:43:46 -07001228 Mutex::Autolock l(mLock);
1229 if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1230 return NO_ERROR;
1231}
Nicolas Catania48290382009-07-10 13:53:06 -07001232
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001233status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
Steve Block3856b092011-10-20 11:56:00 +01001234 ALOGV("[%d] setParameter(%d)", mConnId, key);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001235 switch (key) {
1236 case KEY_PARAMETER_AUDIO_ATTRIBUTES:
1237 {
1238 Mutex::Autolock l(mLock);
1239 return setAudioAttributes_l(request);
1240 }
1241 default:
1242 sp<MediaPlayerBase> p = getPlayer();
1243 if (p == 0) { return UNKNOWN_ERROR; }
1244 return p->setParameter(key, request);
1245 }
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001246}
1247
1248status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
Steve Block3856b092011-10-20 11:56:00 +01001249 ALOGV("[%d] getParameter(%d)", mConnId, key);
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001250 sp<MediaPlayerBase> p = getPlayer();
1251 if (p == 0) return UNKNOWN_ERROR;
1252 return p->getParameter(key, reply);
1253}
1254
John Grossmanc795b642012-02-22 15:38:35 -08001255status_t MediaPlayerService::Client::setRetransmitEndpoint(
1256 const struct sockaddr_in* endpoint) {
1257
1258 if (NULL != endpoint) {
1259 uint32_t a = ntohl(endpoint->sin_addr.s_addr);
1260 uint16_t p = ntohs(endpoint->sin_port);
1261 ALOGV("[%d] setRetransmitEndpoint(%u.%u.%u.%u:%hu)", mConnId,
1262 (a >> 24), (a >> 16) & 0xFF, (a >> 8) & 0xFF, (a & 0xFF), p);
1263 } else {
1264 ALOGV("[%d] setRetransmitEndpoint = <none>", mConnId);
1265 }
1266
1267 sp<MediaPlayerBase> p = getPlayer();
1268
1269 // Right now, the only valid time to set a retransmit endpoint is before
1270 // player selection has been made (since the presence or absence of a
1271 // retransmit endpoint is going to determine which player is selected during
1272 // setDataSource).
1273 if (p != 0) return INVALID_OPERATION;
1274
1275 if (NULL != endpoint) {
1276 mRetransmitEndpoint = *endpoint;
1277 mRetransmitEndpointValid = true;
1278 } else {
1279 mRetransmitEndpointValid = false;
1280 }
1281
1282 return NO_ERROR;
1283}
1284
John Grossman44a7e422012-06-21 17:29:24 -07001285status_t MediaPlayerService::Client::getRetransmitEndpoint(
1286 struct sockaddr_in* endpoint)
1287{
1288 if (NULL == endpoint)
1289 return BAD_VALUE;
1290
1291 sp<MediaPlayerBase> p = getPlayer();
1292
1293 if (p != NULL)
1294 return p->getRetransmitEndpoint(endpoint);
1295
1296 if (!mRetransmitEndpointValid)
1297 return NO_INIT;
1298
1299 *endpoint = mRetransmitEndpoint;
1300
1301 return NO_ERROR;
1302}
1303
Gloria Wangb483c472011-04-11 17:23:27 -07001304void MediaPlayerService::Client::notify(
1305 void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001306{
1307 Client* client = static_cast<Client*>(cookie);
James Dongb8a98252012-08-26 16:13:03 -07001308 if (client == NULL) {
1309 return;
1310 }
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001311
James Dongb8a98252012-08-26 16:13:03 -07001312 sp<IMediaPlayerClient> c;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001313 {
1314 Mutex::Autolock l(client->mLock);
James Dongb8a98252012-08-26 16:13:03 -07001315 c = client->mClient;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001316 if (msg == MEDIA_PLAYBACK_COMPLETE && client->mNextClient != NULL) {
John Grossmancb0b7552012-08-23 17:47:31 -07001317 if (client->mAudioOutput != NULL)
1318 client->mAudioOutput->switchToNextOutput();
Marco Nelissen6b74d672012-02-28 16:07:44 -08001319 client->mNextClient->start();
Wei Jia2afac0c2016-01-07 12:13:07 -08001320 if (client->mNextClient->mClient != NULL) {
1321 client->mNextClient->mClient->notify(
1322 MEDIA_INFO, MEDIA_INFO_STARTED_AS_NEXT, 0, obj);
1323 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001324 }
1325 }
1326
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001327 if (MEDIA_INFO == msg &&
Nicolas Catania48290382009-07-10 13:53:06 -07001328 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikoa64c8c72009-07-20 15:07:26 -07001329 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania48290382009-07-10 13:53:06 -07001330
1331 if(client->shouldDropMetadata(metadata_type)) {
1332 return;
1333 }
1334
1335 // Update the list of metadata that have changed. getMetadata
1336 // also access mMetadataUpdated and clears it.
1337 client->addNewMetadataUpdate(metadata_type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001338 }
James Dongb8a98252012-08-26 16:13:03 -07001339
1340 if (c != NULL) {
1341 ALOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
1342 c->notify(msg, ext1, ext2, obj);
1343 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001344}
1345
Nicolas Catania48290382009-07-10 13:53:06 -07001346
nikoa64c8c72009-07-20 15:07:26 -07001347bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001348{
Nicolas Catania48290382009-07-10 13:53:06 -07001349 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001350
Nicolas Catania48290382009-07-10 13:53:06 -07001351 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001352 return true;
1353 }
1354
Nicolas Catania48290382009-07-10 13:53:06 -07001355 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001356 return false;
Nicolas Catania48290382009-07-10 13:53:06 -07001357 } else {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001358 return true;
1359 }
1360}
1361
Nicolas Catania48290382009-07-10 13:53:06 -07001362
nikoa64c8c72009-07-20 15:07:26 -07001363void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania48290382009-07-10 13:53:06 -07001364 Mutex::Autolock lock(mLock);
1365 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1366 mMetadataUpdated.add(metadata_type);
1367 }
1368}
1369
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001370#if CALLBACK_ANTAGONIZER
1371const int Antagonizer::interval = 10000; // 10 msecs
1372
1373Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1374 mExit(false), mActive(false), mClient(client), mCb(cb)
1375{
1376 createThread(callbackThread, this);
1377}
1378
1379void Antagonizer::kill()
1380{
1381 Mutex::Autolock _l(mLock);
1382 mActive = false;
1383 mExit = true;
1384 mCondition.wait(mLock);
1385}
1386
1387int Antagonizer::callbackThread(void* user)
1388{
Steve Blockb8a80522011-12-20 16:23:08 +00001389 ALOGD("Antagonizer started");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001390 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1391 while (!p->mExit) {
1392 if (p->mActive) {
Steve Block3856b092011-10-20 11:56:00 +01001393 ALOGV("send event");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001394 p->mCb(p->mClient, 0, 0, 0);
1395 }
1396 usleep(interval);
1397 }
1398 Mutex::Autolock _l(p->mLock);
1399 p->mCondition.signal();
Steve Blockb8a80522011-12-20 16:23:08 +00001400 ALOGD("Antagonizer stopped");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001401 return 0;
1402}
1403#endif
1404
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001405#undef LOG_TAG
1406#define LOG_TAG "AudioSink"
Glenn Kastend848eb42016-03-08 13:42:11 -08001407MediaPlayerService::AudioOutput::AudioOutput(audio_session_t sessionId, int uid, int pid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001408 const audio_attributes_t* attr)
Andreas Huber20111aa2009-07-14 16:56:47 -07001409 : mCallback(NULL),
Eric Laurenta514bdb2010-06-21 09:27:30 -07001410 mCallbackCookie(NULL),
Marco Nelissen6b74d672012-02-28 16:07:44 -08001411 mCallbackData(NULL),
Andy Hungd1c74342015-07-07 16:54:23 -07001412 mStreamType(AUDIO_STREAM_MUSIC),
Andy Hungd1c74342015-07-07 16:54:23 -07001413 mLeftVolume(1.0),
1414 mRightVolume(1.0),
1415 mPlaybackRate(AUDIO_PLAYBACK_RATE_DEFAULT),
1416 mSampleRateHz(0),
1417 mMsecsPerFrame(0),
1418 mFrameSize(0),
Eric Laurent1948eb32012-04-13 16:50:19 -07001419 mSessionId(sessionId),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001420 mUid(uid),
Marco Nelissend457c972014-02-11 08:47:07 -08001421 mPid(pid),
Andy Hungd1c74342015-07-07 16:54:23 -07001422 mSendLevel(0.0),
1423 mAuxEffectId(0),
1424 mFlags(AUDIO_OUTPUT_FLAG_NONE)
1425{
Steve Block3856b092011-10-20 11:56:00 +01001426 ALOGV("AudioOutput(%d)", sessionId);
Eric Laurent43562692015-07-15 16:49:07 -07001427 if (attr != NULL) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001428 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1429 if (mAttributes != NULL) {
1430 memcpy(mAttributes, attr, sizeof(audio_attributes_t));
1431 mStreamType = audio_attributes_to_stream_type(attr);
1432 }
1433 } else {
1434 mAttributes = NULL;
Eric Laurent43562692015-07-15 16:49:07 -07001435 }
1436
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001437 setMinBufferCount();
1438}
1439
1440MediaPlayerService::AudioOutput::~AudioOutput()
1441{
1442 close();
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001443 free(mAttributes);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001444 delete mCallbackData;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001445}
1446
Andy Hungd1c74342015-07-07 16:54:23 -07001447//static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001448void MediaPlayerService::AudioOutput::setMinBufferCount()
1449{
1450 char value[PROPERTY_VALUE_MAX];
1451 if (property_get("ro.kernel.qemu", value, 0)) {
1452 mIsOnEmulator = true;
1453 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1454 }
1455}
1456
Andy Hungd1c74342015-07-07 16:54:23 -07001457// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001458bool MediaPlayerService::AudioOutput::isOnEmulator()
1459{
Andy Hungd1c74342015-07-07 16:54:23 -07001460 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001461 return mIsOnEmulator;
1462}
1463
Andy Hungd1c74342015-07-07 16:54:23 -07001464// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001465int MediaPlayerService::AudioOutput::getMinBufferCount()
1466{
Andy Hungd1c74342015-07-07 16:54:23 -07001467 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001468 return mMinBufferCount;
1469}
1470
1471ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1472{
Andy Hungd1c74342015-07-07 16:54:23 -07001473 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001474 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001475 return mTrack->frameCount() * mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001476}
1477
1478ssize_t MediaPlayerService::AudioOutput::frameCount() const
1479{
Andy Hungd1c74342015-07-07 16:54:23 -07001480 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001481 if (mTrack == 0) return NO_INIT;
1482 return mTrack->frameCount();
1483}
1484
1485ssize_t MediaPlayerService::AudioOutput::channelCount() const
1486{
Andy Hungd1c74342015-07-07 16:54:23 -07001487 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001488 if (mTrack == 0) return NO_INIT;
1489 return mTrack->channelCount();
1490}
1491
1492ssize_t MediaPlayerService::AudioOutput::frameSize() const
1493{
Andy Hungd1c74342015-07-07 16:54:23 -07001494 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001495 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001496 return mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001497}
1498
1499uint32_t MediaPlayerService::AudioOutput::latency () const
1500{
Andy Hungd1c74342015-07-07 16:54:23 -07001501 Mutex::Autolock lock(mLock);
Eric Laurentdb354e52012-03-05 17:27:11 -08001502 if (mTrack == 0) return 0;
1503 return mTrack->latency();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001504}
1505
1506float MediaPlayerService::AudioOutput::msecsPerFrame() const
1507{
Andy Hungd1c74342015-07-07 16:54:23 -07001508 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001509 return mMsecsPerFrame;
1510}
1511
Marco Nelissen4110c102012-03-29 09:31:28 -07001512status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position) const
Eric Laurent342e9cf2010-01-19 17:37:09 -08001513{
Andy Hungd1c74342015-07-07 16:54:23 -07001514 Mutex::Autolock lock(mLock);
Eric Laurent342e9cf2010-01-19 17:37:09 -08001515 if (mTrack == 0) return NO_INIT;
1516 return mTrack->getPosition(position);
1517}
1518
Lajos Molnar06ad1522014-08-28 07:27:44 -07001519status_t MediaPlayerService::AudioOutput::getTimestamp(AudioTimestamp &ts) const
1520{
Andy Hungd1c74342015-07-07 16:54:23 -07001521 Mutex::Autolock lock(mLock);
Lajos Molnar06ad1522014-08-28 07:27:44 -07001522 if (mTrack == 0) return NO_INIT;
1523 return mTrack->getTimestamp(ts);
1524}
1525
Wei Jiac4ac8172015-10-21 10:35:48 -07001526// TODO: Remove unnecessary calls to getPlayedOutDurationUs()
1527// as it acquires locks and may query the audio driver.
1528//
1529// Some calls could conceivably retrieve extrapolated data instead of
1530// accessing getTimestamp() or getPosition() every time a data buffer with
1531// a media time is received.
1532//
1533// Calculate duration of played samples if played at normal rate (i.e., 1.0).
1534int64_t MediaPlayerService::AudioOutput::getPlayedOutDurationUs(int64_t nowUs) const
1535{
1536 Mutex::Autolock lock(mLock);
1537 if (mTrack == 0 || mSampleRateHz == 0) {
Wei Jia213f4902015-10-22 08:55:25 -07001538 return 0;
Wei Jiac4ac8172015-10-21 10:35:48 -07001539 }
1540
1541 uint32_t numFramesPlayed;
1542 int64_t numFramesPlayedAt;
1543 AudioTimestamp ts;
1544 static const int64_t kStaleTimestamp100ms = 100000;
1545
1546 status_t res = mTrack->getTimestamp(ts);
1547 if (res == OK) { // case 1: mixing audio tracks and offloaded tracks.
1548 numFramesPlayed = ts.mPosition;
1549 numFramesPlayedAt = ts.mTime.tv_sec * 1000000LL + ts.mTime.tv_nsec / 1000;
1550 const int64_t timestampAge = nowUs - numFramesPlayedAt;
1551 if (timestampAge > kStaleTimestamp100ms) {
1552 // This is an audio FIXME.
1553 // getTimestamp returns a timestamp which may come from audio mixing threads.
1554 // After pausing, the MixerThread may go idle, thus the mTime estimate may
1555 // become stale. Assuming that the MixerThread runs 20ms, with FastMixer at 5ms,
1556 // the max latency should be about 25ms with an average around 12ms (to be verified).
1557 // For safety we use 100ms.
1558 ALOGV("getTimestamp: returned stale timestamp nowUs(%lld) numFramesPlayedAt(%lld)",
1559 (long long)nowUs, (long long)numFramesPlayedAt);
1560 numFramesPlayedAt = nowUs - kStaleTimestamp100ms;
1561 }
1562 //ALOGD("getTimestamp: OK %d %lld", numFramesPlayed, (long long)numFramesPlayedAt);
1563 } else if (res == WOULD_BLOCK) { // case 2: transitory state on start of a new track
1564 numFramesPlayed = 0;
1565 numFramesPlayedAt = nowUs;
1566 //ALOGD("getTimestamp: WOULD_BLOCK %d %lld",
1567 // numFramesPlayed, (long long)numFramesPlayedAt);
1568 } else { // case 3: transitory at new track or audio fast tracks.
1569 res = mTrack->getPosition(&numFramesPlayed);
1570 CHECK_EQ(res, (status_t)OK);
1571 numFramesPlayedAt = nowUs;
1572 numFramesPlayedAt += 1000LL * mTrack->latency() / 2; /* XXX */
1573 //ALOGD("getPosition: %u %lld", numFramesPlayed, (long long)numFramesPlayedAt);
1574 }
1575
1576 // CHECK_EQ(numFramesPlayed & (1 << 31), 0); // can't be negative until 12.4 hrs, test
1577 // TODO: remove the (int32_t) casting below as it may overflow at 12.4 hours.
1578 int64_t durationUs = (int64_t)((int32_t)numFramesPlayed * 1000000LL / mSampleRateHz)
1579 + nowUs - numFramesPlayedAt;
1580 if (durationUs < 0) {
1581 // Occurs when numFramesPlayed position is very small and the following:
1582 // (1) In case 1, the time nowUs is computed before getTimestamp() is called and
1583 // numFramesPlayedAt is greater than nowUs by time more than numFramesPlayed.
1584 // (2) In case 3, using getPosition and adding mAudioSink->latency() to
1585 // numFramesPlayedAt, by a time amount greater than numFramesPlayed.
1586 //
1587 // Both of these are transitory conditions.
1588 ALOGV("getPlayedOutDurationUs: negative duration %lld set to zero", (long long)durationUs);
1589 durationUs = 0;
1590 }
1591 ALOGV("getPlayedOutDurationUs(%lld) nowUs(%lld) frames(%u) framesAt(%lld)",
1592 (long long)durationUs, (long long)nowUs, numFramesPlayed, (long long)numFramesPlayedAt);
1593 return durationUs;
1594}
1595
Marco Nelissen4110c102012-03-29 09:31:28 -07001596status_t MediaPlayerService::AudioOutput::getFramesWritten(uint32_t *frameswritten) const
1597{
Andy Hungd1c74342015-07-07 16:54:23 -07001598 Mutex::Autolock lock(mLock);
Marco Nelissen4110c102012-03-29 09:31:28 -07001599 if (mTrack == 0) return NO_INIT;
Andy Hung2f6e73d2016-04-08 12:12:58 -07001600 ExtendedTimestamp ets;
1601 status_t status = mTrack->getTimestamp(&ets);
1602 if (status == OK || status == WOULD_BLOCK) {
1603 *frameswritten = (uint32_t)ets.mPosition[ExtendedTimestamp::LOCATION_CLIENT];
1604 }
1605 return status;
Marco Nelissen4110c102012-03-29 09:31:28 -07001606}
1607
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001608status_t MediaPlayerService::AudioOutput::setParameters(const String8& keyValuePairs)
1609{
Andy Hungd1c74342015-07-07 16:54:23 -07001610 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001611 if (mTrack == 0) return NO_INIT;
1612 return mTrack->setParameters(keyValuePairs);
1613}
1614
1615String8 MediaPlayerService::AudioOutput::getParameters(const String8& keys)
1616{
Andy Hungd1c74342015-07-07 16:54:23 -07001617 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001618 if (mTrack == 0) return String8::empty();
1619 return mTrack->getParameters(keys);
1620}
1621
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001622void MediaPlayerService::AudioOutput::setAudioAttributes(const audio_attributes_t * attributes) {
Andy Hungd1c74342015-07-07 16:54:23 -07001623 Mutex::Autolock lock(mLock);
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001624 if (attributes == NULL) {
1625 free(mAttributes);
1626 mAttributes = NULL;
1627 } else {
1628 if (mAttributes == NULL) {
1629 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1630 }
1631 memcpy(mAttributes, attributes, sizeof(audio_attributes_t));
Eric Laurent43562692015-07-15 16:49:07 -07001632 mStreamType = audio_attributes_to_stream_type(attributes);
1633 }
1634}
1635
1636void MediaPlayerService::AudioOutput::setAudioStreamType(audio_stream_type_t streamType)
1637{
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001638 Mutex::Autolock lock(mLock);
Eric Laurent43562692015-07-15 16:49:07 -07001639 // do not allow direct stream type modification if attributes have been set
1640 if (mAttributes == NULL) {
1641 mStreamType = streamType;
1642 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001643}
1644
Andy Hungd1c74342015-07-07 16:54:23 -07001645void MediaPlayerService::AudioOutput::deleteRecycledTrack_l()
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001646{
Andy Hungd1c74342015-07-07 16:54:23 -07001647 ALOGV("deleteRecycledTrack_l");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001648 if (mRecycledTrack != 0) {
1649
1650 if (mCallbackData != NULL) {
1651 mCallbackData->setOutput(NULL);
1652 mCallbackData->endTrackSwitch();
1653 }
1654
1655 if ((mRecycledTrack->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) {
Andy Hunge13f8a62016-03-30 14:20:42 -07001656 int32_t msec = 0;
1657 if (!mRecycledTrack->stopped()) { // check if active
1658 (void)mRecycledTrack->pendingDuration(&msec);
1659 }
1660 mRecycledTrack->stop(); // ensure full data drain
1661 ALOGD("deleting recycled track, waiting for data drain (%d msec)", msec);
1662 if (msec > 0) {
1663 static const int32_t WAIT_LIMIT_MS = 3000;
1664 if (msec > WAIT_LIMIT_MS) {
1665 msec = WAIT_LIMIT_MS;
1666 }
1667 usleep(msec * 1000LL);
1668 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001669 }
1670 // An offloaded track isn't flushed because the STREAM_END is reported
1671 // slightly prematurely to allow time for the gapless track switch
1672 // but this means that if we decide not to recycle the track there
1673 // could be a small amount of residual data still playing. We leave
1674 // AudioFlinger to drain the track.
1675
1676 mRecycledTrack.clear();
Andy Hungd1c74342015-07-07 16:54:23 -07001677 close_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001678 delete mCallbackData;
1679 mCallbackData = NULL;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001680 }
1681}
1682
Andy Hungd1c74342015-07-07 16:54:23 -07001683void MediaPlayerService::AudioOutput::close_l()
1684{
1685 mTrack.clear();
1686}
1687
Andreas Huber20111aa2009-07-14 16:56:47 -07001688status_t MediaPlayerService::AudioOutput::open(
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001689 uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
1690 audio_format_t format, int bufferCount,
Eric Laurent1948eb32012-04-13 16:50:19 -07001691 AudioCallback cb, void *cookie,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001692 audio_output_flags_t flags,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001693 const audio_offload_info_t *offloadInfo,
Andy Hung179652e2015-05-31 22:49:46 -07001694 bool doNotReconnect,
1695 uint32_t suggestedFrameCount)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001696{
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001697 ALOGV("open(%u, %d, 0x%x, 0x%x, %d, %d 0x%x)", sampleRate, channelCount, channelMask,
1698 format, bufferCount, mSessionId, flags);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001699
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001700 // offloading is only supported in callback mode for now.
1701 // offloadInfo must be present if offload flag is set
1702 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) &&
1703 ((cb == NULL) || (offloadInfo == NULL))) {
1704 return BAD_VALUE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001705 }
1706
Andy Hung179652e2015-05-31 22:49:46 -07001707 // compute frame count for the AudioTrack internal buffer
1708 size_t frameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001709 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1710 frameCount = 0; // AudioTrack will get frame count from AudioFlinger
1711 } else {
Andy Hung179652e2015-05-31 22:49:46 -07001712 // try to estimate the buffer processing fetch size from AudioFlinger.
1713 // framesPerBuffer is approximate and generally correct, except when it's not :-).
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001714 uint32_t afSampleRate;
1715 size_t afFrameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001716 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1717 return NO_INIT;
1718 }
1719 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1720 return NO_INIT;
1721 }
Andy Hung179652e2015-05-31 22:49:46 -07001722 const size_t framesPerBuffer =
1723 (unsigned long long)sampleRate * afFrameCount / afSampleRate;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001724
Andy Hung179652e2015-05-31 22:49:46 -07001725 if (bufferCount == 0) {
1726 // use suggestedFrameCount
1727 bufferCount = (suggestedFrameCount + framesPerBuffer - 1) / framesPerBuffer;
1728 }
1729 // Check argument bufferCount against the mininum buffer count
1730 if (bufferCount != 0 && bufferCount < mMinBufferCount) {
1731 ALOGV("bufferCount (%d) increased to %d", bufferCount, mMinBufferCount);
1732 bufferCount = mMinBufferCount;
1733 }
1734 // if frameCount is 0, then AudioTrack will get frame count from AudioFlinger
1735 // which will be the minimum size permitted.
1736 frameCount = bufferCount * framesPerBuffer;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001737 }
Andreas Huber20111aa2009-07-14 16:56:47 -07001738
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001739 if (channelMask == CHANNEL_MASK_USE_CHANNEL_ORDER) {
Glenn Kastenab334fd2012-03-14 12:56:06 -07001740 channelMask = audio_channel_out_mask_from_count(channelCount);
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001741 if (0 == channelMask) {
1742 ALOGE("open() error, can\'t derive mask for %d audio channels", channelCount);
1743 return NO_INIT;
1744 }
1745 }
Eric Laurent1948eb32012-04-13 16:50:19 -07001746
Andy Hungd1c74342015-07-07 16:54:23 -07001747 Mutex::Autolock lock(mLock);
Andy Hung179652e2015-05-31 22:49:46 -07001748 mCallback = cb;
1749 mCallbackCookie = cookie;
1750
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001751 // Check whether we can recycle the track
1752 bool reuse = false;
1753 bool bothOffloaded = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001754
Glenn Kasten2799d742013-05-30 14:33:29 -07001755 if (mRecycledTrack != 0) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001756 // check whether we are switching between two offloaded tracks
1757 bothOffloaded = (flags & mRecycledTrack->getFlags()
1758 & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0;
Marco Nelissen67295b52012-06-11 14:52:53 -07001759
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001760 // check if the existing track can be reused as-is, or if a new track needs to be created.
1761 reuse = true;
1762
Marco Nelissen67295b52012-06-11 14:52:53 -07001763 if ((mCallbackData == NULL && mCallback != NULL) ||
1764 (mCallbackData != NULL && mCallback == NULL)) {
1765 // recycled track uses callbacks but the caller wants to use writes, or vice versa
1766 ALOGV("can't chain callback and write");
1767 reuse = false;
1768 } else if ((mRecycledTrack->getSampleRate() != sampleRate) ||
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001769 (mRecycledTrack->channelCount() != (uint32_t)channelCount) ) {
1770 ALOGV("samplerate, channelcount differ: %u/%u Hz, %u/%d ch",
Marco Nelissen67295b52012-06-11 14:52:53 -07001771 mRecycledTrack->getSampleRate(), sampleRate,
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001772 mRecycledTrack->channelCount(), channelCount);
Marco Nelissen67295b52012-06-11 14:52:53 -07001773 reuse = false;
1774 } else if (flags != mFlags) {
1775 ALOGV("output flags differ %08x/%08x", flags, mFlags);
1776 reuse = false;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001777 } else if (mRecycledTrack->format() != format) {
1778 reuse = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001779 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001780 } else {
1781 ALOGV("no track available to recycle");
1782 }
1783
1784 ALOGV_IF(bothOffloaded, "both tracks offloaded");
1785
1786 // If we can't recycle and both tracks are offloaded
1787 // we must close the previous output before opening a new one
1788 if (bothOffloaded && !reuse) {
1789 ALOGV("both offloaded and not recycling");
Andy Hungd1c74342015-07-07 16:54:23 -07001790 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001791 }
1792
1793 sp<AudioTrack> t;
1794 CallbackData *newcbd = NULL;
1795
1796 // We don't attempt to create a new track if we are recycling an
1797 // offloaded track. But, if we are recycling a non-offloaded or we
1798 // are switching where one is offloaded and one isn't then we create
1799 // the new track in advance so that we can read additional stream info
1800
1801 if (!(reuse && bothOffloaded)) {
1802 ALOGV("creating new AudioTrack");
1803
1804 if (mCallback != NULL) {
1805 newcbd = new CallbackData(this);
1806 t = new AudioTrack(
1807 mStreamType,
1808 sampleRate,
1809 format,
1810 channelMask,
1811 frameCount,
1812 flags,
1813 CallbackWrapper,
1814 newcbd,
1815 0, // notification frames
1816 mSessionId,
1817 AudioTrack::TRANSFER_CALLBACK,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001818 offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -08001819 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001820 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001821 mAttributes,
1822 doNotReconnect);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001823 } else {
Andy Hungff874dc2016-04-11 16:49:09 -07001824 // TODO: Due to buffer memory concerns, we use a max target playback speed
1825 // based on mPlaybackRate at the time of open (instead of kMaxRequiredSpeed),
1826 // also clamping the target speed to 1.0 <= targetSpeed <= kMaxRequiredSpeed.
1827 const float targetSpeed =
1828 std::min(std::max(mPlaybackRate.mSpeed, 1.0f), kMaxRequiredSpeed);
1829 ALOGW_IF(targetSpeed != mPlaybackRate.mSpeed,
1830 "track target speed:%f clamped from playback speed:%f",
1831 targetSpeed, mPlaybackRate.mSpeed);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001832 t = new AudioTrack(
1833 mStreamType,
1834 sampleRate,
1835 format,
1836 channelMask,
1837 frameCount,
1838 flags,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001839 NULL, // callback
1840 NULL, // user data
1841 0, // notification frames
1842 mSessionId,
1843 AudioTrack::TRANSFER_DEFAULT,
1844 NULL, // offload info
Marco Nelissend457c972014-02-11 08:47:07 -08001845 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001846 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001847 mAttributes,
Andy Hungff874dc2016-04-11 16:49:09 -07001848 doNotReconnect,
1849 targetSpeed);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001850 }
1851
1852 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1853 ALOGE("Unable to create audio track");
1854 delete newcbd;
Glenn Kasten3e98ecd2015-05-18 13:13:24 -07001855 // t goes out of scope, so reference count drops to zero
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001856 return NO_INIT;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001857 } else {
1858 // successful AudioTrack initialization implies a legacy stream type was generated
1859 // from the audio attributes
1860 mStreamType = t->streamType();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001861 }
1862 }
1863
1864 if (reuse) {
1865 CHECK(mRecycledTrack != NULL);
1866
1867 if (!bothOffloaded) {
1868 if (mRecycledTrack->frameCount() != t->frameCount()) {
Andy Hung833b4752016-04-04 17:15:48 -07001869 ALOGV("framecount differs: %zu/%zu frames",
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001870 mRecycledTrack->frameCount(), t->frameCount());
1871 reuse = false;
1872 }
1873 }
1874
Marco Nelissen67295b52012-06-11 14:52:53 -07001875 if (reuse) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001876 ALOGV("chaining to next output and recycling track");
Andy Hungd1c74342015-07-07 16:54:23 -07001877 close_l();
Marco Nelissen67295b52012-06-11 14:52:53 -07001878 mTrack = mRecycledTrack;
Glenn Kasten2799d742013-05-30 14:33:29 -07001879 mRecycledTrack.clear();
Marco Nelissen67295b52012-06-11 14:52:53 -07001880 if (mCallbackData != NULL) {
1881 mCallbackData->setOutput(this);
1882 }
Marco Nelissen67295b52012-06-11 14:52:53 -07001883 delete newcbd;
Wei Jiae0bbac92016-07-18 16:04:53 -07001884 return updateTrack();
Marco Nelissen67295b52012-06-11 14:52:53 -07001885 }
Marco Nelissen67295b52012-06-11 14:52:53 -07001886 }
1887
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001888 // we're not going to reuse the track, unblock and flush it
1889 // this was done earlier if both tracks are offloaded
1890 if (!bothOffloaded) {
Andy Hungd1c74342015-07-07 16:54:23 -07001891 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001892 }
1893
1894 CHECK((t != NULL) && ((mCallback == NULL) || (newcbd != NULL)));
1895
Marco Nelissen67295b52012-06-11 14:52:53 -07001896 mCallbackData = newcbd;
Steve Block3856b092011-10-20 11:56:00 +01001897 ALOGV("setVolume");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001898 t->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07001899
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001900 mSampleRateHz = sampleRate;
Preetam Singh Ranawat2e17eef2015-08-12 12:11:46 -07001901 mFlags = flags;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001902 mMsecsPerFrame = 1E3f / (mPlaybackRate.mSpeed * sampleRate);
Andy Hungd1c74342015-07-07 16:54:23 -07001903 mFrameSize = t->frameSize();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001904 mTrack = t;
Eric Laurent2beeb502010-07-16 07:43:46 -07001905
Wei Jiae0bbac92016-07-18 16:04:53 -07001906 return updateTrack();
1907}
1908
1909status_t MediaPlayerService::AudioOutput::updateTrack() {
1910 if (mTrack == NULL) {
1911 return NO_ERROR;
1912 }
1913
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001914 status_t res = NO_ERROR;
Wei Jia0162d002015-06-09 11:59:33 -07001915 // Note some output devices may give us a direct track even though we don't specify it.
1916 // Example: Line application b/17459982.
Wei Jiae0bbac92016-07-18 16:04:53 -07001917 if ((mTrack->getFlags()
1918 & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) {
1919 res = mTrack->setPlaybackRate(mPlaybackRate);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001920 if (res == NO_ERROR) {
Wei Jiae0bbac92016-07-18 16:04:53 -07001921 mTrack->setAuxEffectSendLevel(mSendLevel);
1922 res = mTrack->attachAuxEffect(mAuxEffectId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001923 }
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001924 }
Wei Jiae0bbac92016-07-18 16:04:53 -07001925 ALOGV("updateTrack() DONE status %d", res);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001926 return res;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001927}
1928
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001929status_t MediaPlayerService::AudioOutput::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001930{
Steve Block3856b092011-10-20 11:56:00 +01001931 ALOGV("start");
Andy Hungd1c74342015-07-07 16:54:23 -07001932 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001933 if (mCallbackData != NULL) {
1934 mCallbackData->endTrackSwitch();
1935 }
Glenn Kasten2799d742013-05-30 14:33:29 -07001936 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001937 mTrack->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07001938 mTrack->setAuxEffectSendLevel(mSendLevel);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001939 return mTrack->start();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001940 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001941 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001942}
1943
Marco Nelissen6b74d672012-02-28 16:07:44 -08001944void MediaPlayerService::AudioOutput::setNextOutput(const sp<AudioOutput>& nextOutput) {
Andy Hungd1c74342015-07-07 16:54:23 -07001945 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001946 mNextOutput = nextOutput;
1947}
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08001948
Marco Nelissen6b74d672012-02-28 16:07:44 -08001949void MediaPlayerService::AudioOutput::switchToNextOutput() {
1950 ALOGV("switchToNextOutput");
Andy Hungd1c74342015-07-07 16:54:23 -07001951
1952 // Try to acquire the callback lock before moving track (without incurring deadlock).
1953 const unsigned kMaxSwitchTries = 100;
1954 Mutex::Autolock lock(mLock);
1955 for (unsigned tries = 0;;) {
1956 if (mTrack == 0) {
1957 return;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001958 }
Andy Hungd1c74342015-07-07 16:54:23 -07001959 if (mNextOutput != NULL && mNextOutput != this) {
1960 if (mCallbackData != NULL) {
1961 // two alternative approaches
1962#if 1
1963 CallbackData *callbackData = mCallbackData;
1964 mLock.unlock();
1965 // proper acquisition sequence
1966 callbackData->lock();
1967 mLock.lock();
1968 // Caution: it is unlikely that someone deleted our callback or changed our target
1969 if (callbackData != mCallbackData || mNextOutput == NULL || mNextOutput == this) {
1970 // fatal if we are starved out.
1971 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
1972 "switchToNextOutput() cannot obtain correct lock sequence");
1973 callbackData->unlock();
1974 continue;
1975 }
1976 callbackData->mSwitching = true; // begin track switch
Wei Jiaadee56a2016-08-05 15:40:34 -07001977 callbackData->setOutput(NULL);
Andy Hungd1c74342015-07-07 16:54:23 -07001978#else
1979 // tryBeginTrackSwitch() returns false if the callback has the lock.
1980 if (!mCallbackData->tryBeginTrackSwitch()) {
1981 // fatal if we are starved out.
1982 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
1983 "switchToNextOutput() cannot obtain callback lock");
1984 mLock.unlock();
1985 usleep(5 * 1000 /* usec */); // allow callback to use AudioOutput
1986 mLock.lock();
1987 continue;
1988 }
1989#endif
1990 }
1991
1992 Mutex::Autolock nextLock(mNextOutput->mLock);
1993
1994 // If the next output track is not NULL, then it has been
1995 // opened already for playback.
1996 // This is possible even without the next player being started,
1997 // for example, the next player could be prepared and seeked.
1998 //
1999 // Presuming it isn't advisable to force the track over.
2000 if (mNextOutput->mTrack == NULL) {
2001 ALOGD("Recycling track for gapless playback");
2002 delete mNextOutput->mCallbackData;
2003 mNextOutput->mCallbackData = mCallbackData;
2004 mNextOutput->mRecycledTrack = mTrack;
2005 mNextOutput->mSampleRateHz = mSampleRateHz;
2006 mNextOutput->mMsecsPerFrame = mMsecsPerFrame;
Andy Hungd1c74342015-07-07 16:54:23 -07002007 mNextOutput->mFlags = mFlags;
2008 mNextOutput->mFrameSize = mFrameSize;
2009 close_l();
2010 mCallbackData = NULL; // destruction handled by mNextOutput
2011 } else {
2012 ALOGW("Ignoring gapless playback because next player has already started");
2013 // remove track in case resource needed for future players.
2014 if (mCallbackData != NULL) {
2015 mCallbackData->endTrackSwitch(); // release lock for callbacks before close.
2016 }
2017 close_l();
2018 }
2019 }
2020 break;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002021 }
2022}
2023
Wei Jia7d3f4df2015-03-03 15:28:00 -08002024ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002025{
Andy Hungd1c74342015-07-07 16:54:23 -07002026 Mutex::Autolock lock(mLock);
Glenn Kastenadad3d72014-02-21 14:51:43 -08002027 LOG_ALWAYS_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
Andreas Huber20111aa2009-07-14 16:56:47 -07002028
Steve Block3856b092011-10-20 11:56:00 +01002029 //ALOGV("write(%p, %u)", buffer, size);
Glenn Kasten2799d742013-05-30 14:33:29 -07002030 if (mTrack != 0) {
Andy Hung2f6e73d2016-04-08 12:12:58 -07002031 return mTrack->write(buffer, size, blocking);
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07002032 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002033 return NO_INIT;
2034}
2035
2036void MediaPlayerService::AudioOutput::stop()
2037{
Steve Block3856b092011-10-20 11:56:00 +01002038 ALOGV("stop");
Andy Hungd1c74342015-07-07 16:54:23 -07002039 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002040 if (mTrack != 0) mTrack->stop();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002041}
2042
2043void MediaPlayerService::AudioOutput::flush()
2044{
Steve Block3856b092011-10-20 11:56:00 +01002045 ALOGV("flush");
Andy Hungd1c74342015-07-07 16:54:23 -07002046 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002047 if (mTrack != 0) mTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002048}
2049
2050void MediaPlayerService::AudioOutput::pause()
2051{
Steve Block3856b092011-10-20 11:56:00 +01002052 ALOGV("pause");
Andy Hungd1c74342015-07-07 16:54:23 -07002053 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002054 if (mTrack != 0) mTrack->pause();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002055}
2056
2057void MediaPlayerService::AudioOutput::close()
2058{
Steve Block3856b092011-10-20 11:56:00 +01002059 ALOGV("close");
Erik Wolsheimer7845a1f2015-10-30 12:07:52 -07002060 sp<AudioTrack> track;
2061 {
2062 Mutex::Autolock lock(mLock);
2063 track = mTrack;
2064 close_l(); // clears mTrack
2065 }
2066 // destruction of the track occurs outside of mutex.
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002067}
2068
2069void MediaPlayerService::AudioOutput::setVolume(float left, float right)
2070{
Steve Block3856b092011-10-20 11:56:00 +01002071 ALOGV("setVolume(%f, %f)", left, right);
Andy Hungd1c74342015-07-07 16:54:23 -07002072 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002073 mLeftVolume = left;
2074 mRightVolume = right;
Glenn Kasten2799d742013-05-30 14:33:29 -07002075 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002076 mTrack->setVolume(left, right);
2077 }
2078}
2079
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002080status_t MediaPlayerService::AudioOutput::setPlaybackRate(const AudioPlaybackRate &rate)
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002081{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002082 ALOGV("setPlaybackRate(%f %f %d %d)",
2083 rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Andy Hungd1c74342015-07-07 16:54:23 -07002084 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002085 if (mTrack == 0) {
2086 // remember rate so that we can set it when the track is opened
2087 mPlaybackRate = rate;
2088 return OK;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002089 }
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002090 status_t res = mTrack->setPlaybackRate(rate);
2091 if (res != NO_ERROR) {
2092 return res;
2093 }
2094 // rate.mSpeed is always greater than 0 if setPlaybackRate succeeded
2095 CHECK_GT(rate.mSpeed, 0.f);
2096 mPlaybackRate = rate;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002097 if (mSampleRateHz != 0) {
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002098 mMsecsPerFrame = 1E3f / (rate.mSpeed * mSampleRateHz);
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002099 }
2100 return res;
2101}
2102
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002103status_t MediaPlayerService::AudioOutput::getPlaybackRate(AudioPlaybackRate *rate)
2104{
2105 ALOGV("setPlaybackRate");
Andy Hungd1c74342015-07-07 16:54:23 -07002106 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002107 if (mTrack == 0) {
2108 return NO_INIT;
2109 }
2110 *rate = mTrack->getPlaybackRate();
2111 return NO_ERROR;
2112}
2113
Eric Laurent2beeb502010-07-16 07:43:46 -07002114status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
2115{
Steve Block3856b092011-10-20 11:56:00 +01002116 ALOGV("setAuxEffectSendLevel(%f)", level);
Andy Hungd1c74342015-07-07 16:54:23 -07002117 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002118 mSendLevel = level;
Glenn Kasten2799d742013-05-30 14:33:29 -07002119 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002120 return mTrack->setAuxEffectSendLevel(level);
2121 }
2122 return NO_ERROR;
2123}
2124
2125status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
2126{
Steve Block3856b092011-10-20 11:56:00 +01002127 ALOGV("attachAuxEffect(%d)", effectId);
Andy Hungd1c74342015-07-07 16:54:23 -07002128 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002129 mAuxEffectId = effectId;
Glenn Kasten2799d742013-05-30 14:33:29 -07002130 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002131 return mTrack->attachAuxEffect(effectId);
2132 }
2133 return NO_ERROR;
2134}
2135
Andreas Huber20111aa2009-07-14 16:56:47 -07002136// static
2137void MediaPlayerService::AudioOutput::CallbackWrapper(
Glenn Kastend217a8c2011-06-01 15:20:35 -07002138 int event, void *cookie, void *info) {
Steve Block3856b092011-10-20 11:56:00 +01002139 //ALOGV("callbackwrapper");
Marco Nelissen6b74d672012-02-28 16:07:44 -08002140 CallbackData *data = (CallbackData*)cookie;
Andy Hungd1c74342015-07-07 16:54:23 -07002141 // lock to ensure we aren't caught in the middle of a track switch.
Marco Nelissen6b74d672012-02-28 16:07:44 -08002142 data->lock();
2143 AudioOutput *me = data->getOutput();
Andreas Huber20111aa2009-07-14 16:56:47 -07002144 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002145 if (me == NULL) {
2146 // no output set, likely because the track was scheduled to be reused
2147 // by another player, but the format turned out to be incompatible.
2148 data->unlock();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002149 if (buffer != NULL) {
2150 buffer->size = 0;
2151 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08002152 return;
2153 }
Andreas Huber20111aa2009-07-14 16:56:47 -07002154
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002155 switch(event) {
2156 case AudioTrack::EVENT_MORE_DATA: {
2157 size_t actualSize = (*me->mCallback)(
2158 me, buffer->raw, buffer->size, me->mCallbackCookie,
2159 CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002160
Andy Hung719b46b2015-05-31 22:18:25 -07002161 // Log when no data is returned from the callback.
2162 // (1) We may have no data (especially with network streaming sources).
2163 // (2) We may have reached the EOS and the audio track is not stopped yet.
2164 // Note that AwesomePlayer/AudioPlayer will only return zero size when it reaches the EOS.
2165 // NuPlayerRenderer will return zero when it doesn't have data (it doesn't block to fill).
2166 //
2167 // This is a benign busy-wait, with the next data request generated 10 ms or more later;
2168 // nevertheless for power reasons, we don't want to see too many of these.
Andreas Huber2e8ffaf2010-02-18 16:45:13 -08002169
Andy Hung719b46b2015-05-31 22:18:25 -07002170 ALOGV_IF(actualSize == 0 && buffer->size > 0, "callbackwrapper: empty buffer returned");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002171
2172 buffer->size = actualSize;
2173 } break;
2174
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002175 case AudioTrack::EVENT_STREAM_END:
Andy Hung719b46b2015-05-31 22:18:25 -07002176 // currently only occurs for offloaded callbacks
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002177 ALOGV("callbackwrapper: deliver EVENT_STREAM_END");
2178 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2179 me->mCallbackCookie, CB_EVENT_STREAM_END);
2180 break;
2181
2182 case AudioTrack::EVENT_NEW_IAUDIOTRACK :
2183 ALOGV("callbackwrapper: deliver EVENT_TEAR_DOWN");
2184 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2185 me->mCallbackCookie, CB_EVENT_TEAR_DOWN);
2186 break;
2187
Glenn Kasten421743b2015-06-01 08:18:08 -07002188 case AudioTrack::EVENT_UNDERRUN:
Andy Hung719b46b2015-05-31 22:18:25 -07002189 // This occurs when there is no data available, typically
Glenn Kasten421743b2015-06-01 08:18:08 -07002190 // when there is a failure to supply data to the AudioTrack. It can also
2191 // occur in non-offloaded mode when the audio device comes out of standby.
2192 //
Andy Hung719b46b2015-05-31 22:18:25 -07002193 // If an AudioTrack underruns it outputs silence. Since this happens suddenly
2194 // it may sound like an audible pop or glitch.
2195 //
2196 // The underrun event is sent once per track underrun; the condition is reset
2197 // when more data is sent to the AudioTrack.
Eric Laurente93cc032016-05-05 10:15:10 -07002198 ALOGD("callbackwrapper: EVENT_UNDERRUN (discarded)");
Glenn Kasten421743b2015-06-01 08:18:08 -07002199 break;
2200
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002201 default:
2202 ALOGE("received unknown event type: %d inside CallbackWrapper !", event);
Andreas Huber51c1e0e2011-04-04 11:43:40 -07002203 }
2204
Marco Nelissen6b74d672012-02-28 16:07:44 -08002205 data->unlock();
Andreas Huber20111aa2009-07-14 16:56:47 -07002206}
2207
Glenn Kastend848eb42016-03-08 13:42:11 -08002208audio_session_t MediaPlayerService::AudioOutput::getSessionId() const
Eric Laurent8c563ed2010-10-07 18:23:03 -07002209{
Andy Hungd1c74342015-07-07 16:54:23 -07002210 Mutex::Autolock lock(mLock);
Eric Laurent8c563ed2010-10-07 18:23:03 -07002211 return mSessionId;
2212}
2213
Eric Laurent6f59db12013-07-26 17:16:50 -07002214uint32_t MediaPlayerService::AudioOutput::getSampleRate() const
2215{
Andy Hungd1c74342015-07-07 16:54:23 -07002216 Mutex::Autolock lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -07002217 if (mTrack == 0) return 0;
2218 return mTrack->getSampleRate();
2219}
2220
Andy Hungf2c87b32016-04-07 19:49:29 -07002221int64_t MediaPlayerService::AudioOutput::getBufferDurationInUs() const
2222{
2223 Mutex::Autolock lock(mLock);
2224 if (mTrack == 0) {
2225 return 0;
2226 }
2227 int64_t duration;
2228 if (mTrack->getBufferDurationInUs(&duration) != OK) {
2229 return 0;
2230 }
2231 return duration;
2232}
2233
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002234////////////////////////////////////////////////////////////////////////////////
2235
2236struct CallbackThread : public Thread {
2237 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
2238 MediaPlayerBase::AudioSink::AudioCallback cb,
2239 void *cookie);
2240
2241protected:
2242 virtual ~CallbackThread();
2243
2244 virtual bool threadLoop();
2245
2246private:
2247 wp<MediaPlayerBase::AudioSink> mSink;
2248 MediaPlayerBase::AudioSink::AudioCallback mCallback;
2249 void *mCookie;
2250 void *mBuffer;
2251 size_t mBufferSize;
2252
2253 CallbackThread(const CallbackThread &);
2254 CallbackThread &operator=(const CallbackThread &);
2255};
2256
2257CallbackThread::CallbackThread(
2258 const wp<MediaPlayerBase::AudioSink> &sink,
2259 MediaPlayerBase::AudioSink::AudioCallback cb,
2260 void *cookie)
2261 : mSink(sink),
2262 mCallback(cb),
2263 mCookie(cookie),
2264 mBuffer(NULL),
2265 mBufferSize(0) {
2266}
2267
2268CallbackThread::~CallbackThread() {
2269 if (mBuffer) {
2270 free(mBuffer);
2271 mBuffer = NULL;
2272 }
2273}
2274
2275bool CallbackThread::threadLoop() {
2276 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
2277 if (sink == NULL) {
2278 return false;
2279 }
2280
2281 if (mBuffer == NULL) {
2282 mBufferSize = sink->bufferSize();
2283 mBuffer = malloc(mBufferSize);
2284 }
2285
2286 size_t actualSize =
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002287 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie,
2288 MediaPlayerBase::AudioSink::CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002289
2290 if (actualSize > 0) {
2291 sink->write(mBuffer, actualSize);
Andy Hunga31335a2014-08-20 17:37:59 -07002292 // Could return false on sink->write() error or short count.
2293 // Not necessarily appropriate but would work for AudioCache behavior.
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002294 }
2295
2296 return true;
2297}
2298
2299////////////////////////////////////////////////////////////////////////////////
2300
Gloria Wang7cf180c2011-02-19 18:37:57 -08002301void MediaPlayerService::addBatteryData(uint32_t params)
2302{
2303 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002304
2305 int32_t time = systemTime() / 1000000L;
2306
2307 // change audio output devices. This notification comes from AudioFlinger
2308 if ((params & kBatteryDataSpeakerOn)
2309 || (params & kBatteryDataOtherAudioDeviceOn)) {
2310
2311 int deviceOn[NUM_AUDIO_DEVICES];
2312 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2313 deviceOn[i] = 0;
2314 }
2315
2316 if ((params & kBatteryDataSpeakerOn)
2317 && (params & kBatteryDataOtherAudioDeviceOn)) {
2318 deviceOn[SPEAKER_AND_OTHER] = 1;
2319 } else if (params & kBatteryDataSpeakerOn) {
2320 deviceOn[SPEAKER] = 1;
2321 } else {
2322 deviceOn[OTHER_AUDIO_DEVICE] = 1;
2323 }
2324
2325 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2326 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
2327
2328 if (mBatteryAudio.refCount > 0) { // if playing audio
2329 if (!deviceOn[i]) {
2330 mBatteryAudio.lastTime[i] += time;
2331 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2332 mBatteryAudio.lastTime[i] = 0;
2333 } else {
2334 mBatteryAudio.lastTime[i] = 0 - time;
2335 }
2336 }
2337
2338 mBatteryAudio.deviceOn[i] = deviceOn[i];
2339 }
2340 }
2341 return;
2342 }
2343
Marco Nelissenb7848f12014-12-04 08:57:56 -08002344 // an audio stream is started
Gloria Wang9ee159b2011-02-24 14:51:45 -08002345 if (params & kBatteryDataAudioFlingerStart) {
2346 // record the start time only if currently no other audio
2347 // is being played
2348 if (mBatteryAudio.refCount == 0) {
2349 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2350 if (mBatteryAudio.deviceOn[i]) {
2351 mBatteryAudio.lastTime[i] -= time;
2352 }
2353 }
2354 }
2355
2356 mBatteryAudio.refCount ++;
2357 return;
2358
2359 } else if (params & kBatteryDataAudioFlingerStop) {
2360 if (mBatteryAudio.refCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002361 ALOGW("Battery track warning: refCount is <= 0");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002362 return;
2363 }
2364
2365 // record the stop time only if currently this is the only
2366 // audio being played
2367 if (mBatteryAudio.refCount == 1) {
2368 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2369 if (mBatteryAudio.deviceOn[i]) {
2370 mBatteryAudio.lastTime[i] += time;
2371 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2372 mBatteryAudio.lastTime[i] = 0;
2373 }
2374 }
2375 }
2376
2377 mBatteryAudio.refCount --;
2378 return;
2379 }
2380
Gloria Wang7cf180c2011-02-19 18:37:57 -08002381 int uid = IPCThreadState::self()->getCallingUid();
2382 if (uid == AID_MEDIA) {
2383 return;
2384 }
2385 int index = mBatteryData.indexOfKey(uid);
Gloria Wang7cf180c2011-02-19 18:37:57 -08002386
2387 if (index < 0) { // create a new entry for this UID
2388 BatteryUsageInfo info;
2389 info.audioTotalTime = 0;
2390 info.videoTotalTime = 0;
2391 info.audioLastTime = 0;
2392 info.videoLastTime = 0;
2393 info.refCount = 0;
2394
Gloria Wang9ee159b2011-02-24 14:51:45 -08002395 if (mBatteryData.add(uid, info) == NO_MEMORY) {
Steve Block29357bc2012-01-06 19:20:56 +00002396 ALOGE("Battery track error: no memory for new app");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002397 return;
2398 }
Gloria Wang7cf180c2011-02-19 18:37:57 -08002399 }
2400
2401 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
2402
2403 if (params & kBatteryDataCodecStarted) {
2404 if (params & kBatteryDataTrackAudio) {
2405 info.audioLastTime -= time;
2406 info.refCount ++;
2407 }
2408 if (params & kBatteryDataTrackVideo) {
2409 info.videoLastTime -= time;
2410 info.refCount ++;
2411 }
2412 } else {
2413 if (info.refCount == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002414 ALOGW("Battery track warning: refCount is already 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002415 return;
2416 } else if (info.refCount < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00002417 ALOGE("Battery track error: refCount < 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002418 mBatteryData.removeItem(uid);
2419 return;
2420 }
2421
2422 if (params & kBatteryDataTrackAudio) {
2423 info.audioLastTime += time;
2424 info.refCount --;
2425 }
2426 if (params & kBatteryDataTrackVideo) {
2427 info.videoLastTime += time;
2428 info.refCount --;
2429 }
2430
2431 // no stream is being played by this UID
2432 if (info.refCount == 0) {
2433 info.audioTotalTime += info.audioLastTime;
2434 info.audioLastTime = 0;
2435 info.videoTotalTime += info.videoLastTime;
2436 info.videoLastTime = 0;
2437 }
2438 }
2439}
2440
2441status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
2442 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002443
2444 // audio output devices usage
2445 int32_t time = systemTime() / 1000000L; //in ms
2446 int32_t totalTime;
2447
2448 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2449 totalTime = mBatteryAudio.totalTime[i];
2450
2451 if (mBatteryAudio.deviceOn[i]
2452 && (mBatteryAudio.lastTime[i] != 0)) {
2453 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
2454 totalTime += tmpTime;
2455 }
2456
2457 reply->writeInt32(totalTime);
2458 // reset the total time
2459 mBatteryAudio.totalTime[i] = 0;
2460 }
2461
2462 // codec usage
Gloria Wang7cf180c2011-02-19 18:37:57 -08002463 BatteryUsageInfo info;
2464 int size = mBatteryData.size();
2465
2466 reply->writeInt32(size);
2467 int i = 0;
2468
2469 while (i < size) {
2470 info = mBatteryData.valueAt(i);
2471
2472 reply->writeInt32(mBatteryData.keyAt(i)); //UID
2473 reply->writeInt32(info.audioTotalTime);
2474 reply->writeInt32(info.videoTotalTime);
2475
2476 info.audioTotalTime = 0;
2477 info.videoTotalTime = 0;
2478
2479 // remove the UID entry where no stream is being played
2480 if (info.refCount <= 0) {
2481 mBatteryData.removeItemsAt(i);
2482 size --;
2483 i --;
2484 }
2485 i++;
2486 }
2487 return NO_ERROR;
2488}
nikoa64c8c72009-07-20 15:07:26 -07002489} // namespace android