blob: 8bb108678c359036b7314834fc5e817bc779ed4b [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
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070085namespace {
nikoa64c8c72009-07-20 15:07:26 -070086using android::media::Metadata;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070087using android::status_t;
88using android::OK;
89using android::BAD_VALUE;
90using android::NOT_ENOUGH_DATA;
91using android::Parcel;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070092
93// Max number of entries in the filter.
94const int kMaxFilterSize = 64; // I pulled that out of thin air.
95
Andy Hungff874dc2016-04-11 16:49:09 -070096const float kMaxRequiredSpeed = 8.0f; // for PCM tracks allow up to 8x speedup.
97
nikoa64c8c72009-07-20 15:07:26 -070098// FIXME: Move all the metadata related function in the Metadata.cpp
nikod608a812009-07-16 16:39:53 -070099
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700100
101// Unmarshall a filter from a Parcel.
102// Filter format in a parcel:
103//
104// 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
105// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
106// | number of entries (n) |
107// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
108// | metadata type 1 |
109// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
110// | metadata type 2 |
111// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
112// ....
113// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
114// | metadata type n |
115// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
116//
117// @param p Parcel that should start with a filter.
118// @param[out] filter On exit contains the list of metadata type to be
119// filtered.
120// @param[out] status On exit contains the status code to be returned.
121// @return true if the parcel starts with a valid filter.
122bool unmarshallFilter(const Parcel& p,
nikoa64c8c72009-07-20 15:07:26 -0700123 Metadata::Filter *filter,
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700124 status_t *status)
125{
Nicolas Catania48290382009-07-10 13:53:06 -0700126 int32_t val;
127 if (p.readInt32(&val) != OK)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700128 {
Steve Block29357bc2012-01-06 19:20:56 +0000129 ALOGE("Failed to read filter's length");
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700130 *status = NOT_ENOUGH_DATA;
131 return false;
132 }
133
Nicolas Catania48290382009-07-10 13:53:06 -0700134 if( val > kMaxFilterSize || val < 0)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700135 {
Steve Block29357bc2012-01-06 19:20:56 +0000136 ALOGE("Invalid filter len %d", val);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700137 *status = BAD_VALUE;
138 return false;
139 }
140
Nicolas Catania48290382009-07-10 13:53:06 -0700141 const size_t num = val;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700142
143 filter->clear();
Nicolas Catania48290382009-07-10 13:53:06 -0700144 filter->setCapacity(num);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700145
nikoa64c8c72009-07-20 15:07:26 -0700146 size_t size = num * sizeof(Metadata::Type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700147
Nicolas Catania48290382009-07-10 13:53:06 -0700148
149 if (p.dataAvail() < size)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700150 {
Andy Hung833b4752016-04-04 17:15:48 -0700151 ALOGE("Filter too short expected %zu but got %zu", size, p.dataAvail());
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700152 *status = NOT_ENOUGH_DATA;
153 return false;
154 }
155
nikoa64c8c72009-07-20 15:07:26 -0700156 const Metadata::Type *data =
157 static_cast<const Metadata::Type*>(p.readInplace(size));
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700158
Nicolas Catania48290382009-07-10 13:53:06 -0700159 if (NULL == data)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700160 {
Steve Block29357bc2012-01-06 19:20:56 +0000161 ALOGE("Filter had no data");
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700162 *status = BAD_VALUE;
163 return false;
164 }
165
166 // TODO: The stl impl of vector would be more efficient here
167 // because it degenerates into a memcpy on pod types. Try to
168 // replace later or use stl::set.
Nicolas Catania48290382009-07-10 13:53:06 -0700169 for (size_t i = 0; i < num; ++i)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700170 {
Nicolas Catania48290382009-07-10 13:53:06 -0700171 filter->add(*data);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700172 ++data;
173 }
174 *status = OK;
175 return true;
176}
177
Nicolas Catania48290382009-07-10 13:53:06 -0700178// @param filter Of metadata type.
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700179// @param val To be searched.
180// @return true if a match was found.
nikoa64c8c72009-07-20 15:07:26 -0700181bool findMetadata(const Metadata::Filter& filter, const int32_t val)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700182{
183 // Deal with empty and ANY right away
184 if (filter.isEmpty()) return false;
nikoa64c8c72009-07-20 15:07:26 -0700185 if (filter[0] == Metadata::kAny) return true;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700186
Nicolas Catania48290382009-07-10 13:53:06 -0700187 return filter.indexOf(val) >= 0;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700188}
189
190} // anonymous namespace
191
192
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700193namespace {
194using android::Parcel;
195using android::String16;
196
197// marshalling tag indicating flattened utf16 tags
198// keep in sync with frameworks/base/media/java/android/media/AudioAttributes.java
199const int32_t kAudioAttributesMarshallTagFlattenTags = 1;
200
201// Audio attributes format in a parcel:
202//
203// 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
204// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
205// | usage |
206// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
207// | content_type |
208// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Hyejin Kim4f418f92014-09-05 15:50:03 +0900209// | source |
210// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700211// | flags |
212// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
213// | kAudioAttributesMarshallTagFlattenTags | // ignore tags if not found
214// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
215// | flattened tags in UTF16 |
216// | ... |
217// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
218//
219// @param p Parcel that contains audio attributes.
220// @param[out] attributes On exit points to an initialized audio_attributes_t structure
221// @param[out] status On exit contains the status code to be returned.
222void unmarshallAudioAttributes(const Parcel& parcel, audio_attributes_t *attributes)
223{
224 attributes->usage = (audio_usage_t) parcel.readInt32();
225 attributes->content_type = (audio_content_type_t) parcel.readInt32();
Hyejin Kim4f418f92014-09-05 15:50:03 +0900226 attributes->source = (audio_source_t) parcel.readInt32();
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700227 attributes->flags = (audio_flags_mask_t) parcel.readInt32();
228 const bool hasFlattenedTag = (parcel.readInt32() == kAudioAttributesMarshallTagFlattenTags);
229 if (hasFlattenedTag) {
230 // the tags are UTF16, convert to UTF8
231 String16 tags = parcel.readString16();
232 ssize_t realTagSize = utf16_to_utf8_length(tags.string(), tags.size());
233 if (realTagSize <= 0) {
234 strcpy(attributes->tags, "");
235 } else {
236 // copy the flattened string into the attributes as the destination for the conversion:
237 // copying array size -1, array for tags was calloc'd, no need to NULL-terminate it
238 size_t tagSize = realTagSize > AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 ?
239 AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 : realTagSize;
240 utf16_to_utf8(tags.string(), tagSize, attributes->tags);
241 }
242 } else {
243 ALOGE("unmarshallAudioAttributes() received unflattened tags, ignoring tag values");
244 strcpy(attributes->tags, "");
245 }
246}
247} // anonymous namespace
248
249
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800250namespace android {
251
Marco Nelissenf09611f2015-02-13 14:12:42 -0800252extern ALooperRoster gLooperRoster;
253
254
Dave Burked681bbb2011-08-30 14:39:17 +0100255static bool checkPermission(const char* permissionString) {
Dave Burked681bbb2011-08-30 14:39:17 +0100256 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
257 bool ok = checkCallingPermission(String16(permissionString));
Steve Block29357bc2012-01-06 19:20:56 +0000258 if (!ok) ALOGE("Request requires %s", permissionString);
Dave Burked681bbb2011-08-30 14:39:17 +0100259 return ok;
260}
261
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800262// 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 -0800263/* static */ int MediaPlayerService::AudioOutput::mMinBufferCount = 4;
264/* static */ bool MediaPlayerService::AudioOutput::mIsOnEmulator = false;
265
266void MediaPlayerService::instantiate() {
267 defaultServiceManager()->addService(
268 String16("media.player"), new MediaPlayerService());
269}
270
271MediaPlayerService::MediaPlayerService()
272{
Steve Block3856b092011-10-20 11:56:00 +0100273 ALOGV("MediaPlayerService created");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800274 mNextConnId = 1;
Gloria Wang9ee159b2011-02-24 14:51:45 -0800275
276 mBatteryAudio.refCount = 0;
277 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
278 mBatteryAudio.deviceOn[i] = 0;
279 mBatteryAudio.lastTime[i] = 0;
280 mBatteryAudio.totalTime[i] = 0;
281 }
282 // speaker is on by default
283 mBatteryAudio.deviceOn[SPEAKER] = 1;
John Grossman44a7e422012-06-21 17:29:24 -0700284
Chong Zhang0b30fd42014-07-23 14:46:05 -0700285 // reset battery stats
286 // if the mediaserver has crashed, battery stats could be left
287 // in bad state, reset the state upon service start.
Wei Jia3f273d12015-11-24 09:06:49 -0800288 BatteryNotifier::getInstance().noteResetVideo();
Chong Zhang0b30fd42014-07-23 14:46:05 -0700289
John Grossman44a7e422012-06-21 17:29:24 -0700290 MediaPlayerFactory::registerBuiltinFactories();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800291}
292
293MediaPlayerService::~MediaPlayerService()
294{
Steve Block3856b092011-10-20 11:56:00 +0100295 ALOGV("MediaPlayerService destroyed");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800296}
297
Svet Ganovbe71aa22015-04-28 12:06:02 -0700298sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(const String16 &opPackageName)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800299{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800300 pid_t pid = IPCThreadState::self()->getCallingPid();
Svet Ganovbe71aa22015-04-28 12:06:02 -0700301 sp<MediaRecorderClient> recorder = new MediaRecorderClient(this, pid, opPackageName);
Gloria Wangdac6a312009-10-29 15:46:37 -0700302 wp<MediaRecorderClient> w = recorder;
303 Mutex::Autolock lock(mLock);
304 mMediaRecorderClients.add(w);
Steve Block3856b092011-10-20 11:56:00 +0100305 ALOGV("Create new media recorder client from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800306 return recorder;
307}
308
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -0700309void MediaPlayerService::removeMediaRecorderClient(const wp<MediaRecorderClient>& client)
Gloria Wangdac6a312009-10-29 15:46:37 -0700310{
311 Mutex::Autolock lock(mLock);
312 mMediaRecorderClients.remove(client);
Steve Block3856b092011-10-20 11:56:00 +0100313 ALOGV("Delete media recorder client");
Gloria Wangdac6a312009-10-29 15:46:37 -0700314}
315
Glenn Kastenf37971f2012-02-03 11:06:53 -0800316sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800317{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800318 pid_t pid = IPCThreadState::self()->getCallingPid();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800319 sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
Steve Block3856b092011-10-20 11:56:00 +0100320 ALOGV("Create new media retriever from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800321 return retriever;
322}
323
Glenn Kastenf37971f2012-02-03 11:06:53 -0800324sp<IMediaPlayer> MediaPlayerService::create(const sp<IMediaPlayerClient>& client,
Glenn Kastend848eb42016-03-08 13:42:11 -0800325 audio_session_t audioSessionId)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800326{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800327 pid_t pid = IPCThreadState::self()->getCallingPid();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800328 int32_t connId = android_atomic_inc(&mNextConnId);
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700329
330 sp<Client> c = new Client(
331 this, pid, connId, client, audioSessionId,
332 IPCThreadState::self()->getCallingUid());
333
Steve Block3856b092011-10-20 11:56:00 +0100334 ALOGV("Create new client(%d) from pid %d, uid %d, ", connId, pid,
Dave Burked681bbb2011-08-30 14:39:17 +0100335 IPCThreadState::self()->getCallingUid());
336
337 wp<Client> w = c;
338 {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800339 Mutex::Autolock lock(mLock);
340 mClients.add(w);
341 }
Andreas Hubere2b10282010-11-23 11:41:34 -0800342 return c;
343}
344
Lajos Molnar1381d4b2014-08-07 15:18:35 -0700345sp<IMediaCodecList> MediaPlayerService::getCodecList() const {
346 return MediaCodecList::getLocalInstance();
347}
348
Marco Nelissen260e56c2016-01-28 21:41:25 +0000349sp<IOMX> MediaPlayerService::getOMX() {
Marco Nelissen1900e772016-02-02 16:12:16 -0800350 ALOGI("MediaPlayerService::getOMX");
Marco Nelissen260e56c2016-01-28 21:41:25 +0000351 Mutex::Autolock autoLock(mLock);
352
353 if (mOMX.get() == NULL) {
354 mOMX = new OMX;
355 }
356
357 return mOMX;
358}
359
Andreas Huber279dcd82013-01-30 10:41:25 -0800360sp<IHDCP> MediaPlayerService::makeHDCP(bool createEncryptionModule) {
361 return new HDCP(createEncryptionModule);
Andreas Huber59451f82012-09-18 10:36:32 -0700362}
363
Jeff Brown2013a542012-09-04 21:38:42 -0700364sp<IRemoteDisplay> MediaPlayerService::listenForRemoteDisplay(
Svet Ganovbe71aa22015-04-28 12:06:02 -0700365 const String16 &opPackageName,
Jeff Brown2013a542012-09-04 21:38:42 -0700366 const sp<IRemoteDisplayClient>& client, const String8& iface) {
Jeff Brownaba33d52012-09-07 17:38:58 -0700367 if (!checkPermission("android.permission.CONTROL_WIFI_DISPLAY")) {
368 return NULL;
369 }
370
Svet Ganovbe71aa22015-04-28 12:06:02 -0700371 return new RemoteDisplay(opPackageName, client, iface.string());
Jeff Brown2013a542012-09-04 21:38:42 -0700372}
373
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800374status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
375{
376 const size_t SIZE = 256;
377 char buffer[SIZE];
378 String8 result;
379
380 result.append(" AudioOutput\n");
381 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n",
382 mStreamType, mLeftVolume, mRightVolume);
383 result.append(buffer);
384 snprintf(buffer, 255, " msec per frame(%f), latency (%d)\n",
Eric Laurentdb354e52012-03-05 17:27:11 -0800385 mMsecsPerFrame, (mTrack != 0) ? mTrack->latency() : -1);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800386 result.append(buffer);
Eric Laurent2beeb502010-07-16 07:43:46 -0700387 snprintf(buffer, 255, " aux effect id(%d), send level (%f)\n",
388 mAuxEffectId, mSendLevel);
389 result.append(buffer);
390
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800391 ::write(fd, result.string(), result.size());
392 if (mTrack != 0) {
393 mTrack->dump(fd, args);
394 }
395 return NO_ERROR;
396}
397
Lajos Molnar6d339f12015-04-17 16:15:53 -0700398status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800399{
400 const size_t SIZE = 256;
401 char buffer[SIZE];
402 String8 result;
403 result.append(" Client\n");
404 snprintf(buffer, 255, " pid(%d), connId(%d), status(%d), looping(%s)\n",
405 mPid, mConnId, mStatus, mLoop?"true": "false");
406 result.append(buffer);
407 write(fd, result.string(), result.size());
Andreas Hubera0b1d4b2011-06-07 15:52:25 -0700408 if (mPlayer != NULL) {
409 mPlayer->dump(fd, args);
410 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800411 if (mAudioOutput != 0) {
412 mAudioOutput->dump(fd, args);
413 }
414 write(fd, "\n", 1);
415 return NO_ERROR;
416}
417
Marco Nelissenf09611f2015-02-13 14:12:42 -0800418/**
419 * The only arguments this understands right now are -c, -von and -voff,
420 * which are parsed by ALooperRoster::dump()
421 */
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800422status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
423{
424 const size_t SIZE = 256;
425 char buffer[SIZE];
426 String8 result;
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530427 SortedVector< sp<Client> > clients; //to serialise the mutex unlock & client destruction.
428 SortedVector< sp<MediaRecorderClient> > mediaRecorderClients;
429
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800430 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
431 snprintf(buffer, SIZE, "Permission Denial: "
432 "can't dump MediaPlayerService from pid=%d, uid=%d\n",
433 IPCThreadState::self()->getCallingPid(),
434 IPCThreadState::self()->getCallingUid());
435 result.append(buffer);
436 } else {
437 Mutex::Autolock lock(mLock);
438 for (int i = 0, n = mClients.size(); i < n; ++i) {
439 sp<Client> c = mClients[i].promote();
440 if (c != 0) c->dump(fd, args);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530441 clients.add(c);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800442 }
James Dongb9141222010-07-08 11:16:11 -0700443 if (mMediaRecorderClients.size() == 0) {
444 result.append(" No media recorder client\n\n");
445 } else {
446 for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
447 sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
James Donge579e282011-10-18 22:29:20 -0700448 if (c != 0) {
449 snprintf(buffer, 255, " MediaRecorderClient pid(%d)\n", c->mPid);
450 result.append(buffer);
451 write(fd, result.string(), result.size());
452 result = "\n";
453 c->dump(fd, args);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530454 mediaRecorderClients.add(c);
James Donge579e282011-10-18 22:29:20 -0700455 }
James Dongb9141222010-07-08 11:16:11 -0700456 }
Gloria Wangdac6a312009-10-29 15:46:37 -0700457 }
458
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800459 result.append(" Files opened and/or mapped:\n");
Marco Nelissenf09611f2015-02-13 14:12:42 -0800460 snprintf(buffer, SIZE, "/proc/%d/maps", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800461 FILE *f = fopen(buffer, "r");
462 if (f) {
463 while (!feof(f)) {
464 fgets(buffer, SIZE, f);
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700465 if (strstr(buffer, " /storage/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800466 strstr(buffer, " /system/sounds/") ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700467 strstr(buffer, " /data/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800468 strstr(buffer, " /system/media/")) {
469 result.append(" ");
470 result.append(buffer);
471 }
472 }
473 fclose(f);
474 } else {
475 result.append("couldn't open ");
476 result.append(buffer);
477 result.append("\n");
478 }
479
Marco Nelissenf09611f2015-02-13 14:12:42 -0800480 snprintf(buffer, SIZE, "/proc/%d/fd", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800481 DIR *d = opendir(buffer);
482 if (d) {
483 struct dirent *ent;
484 while((ent = readdir(d)) != NULL) {
485 if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
Marco Nelissenf09611f2015-02-13 14:12:42 -0800486 snprintf(buffer, SIZE, "/proc/%d/fd/%s", getpid(), ent->d_name);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800487 struct stat s;
488 if (lstat(buffer, &s) == 0) {
489 if ((s.st_mode & S_IFMT) == S_IFLNK) {
490 char linkto[256];
491 int len = readlink(buffer, linkto, sizeof(linkto));
492 if(len > 0) {
493 if(len > 255) {
494 linkto[252] = '.';
495 linkto[253] = '.';
496 linkto[254] = '.';
497 linkto[255] = 0;
498 } else {
499 linkto[len] = 0;
500 }
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700501 if (strstr(linkto, "/storage/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800502 strstr(linkto, "/system/sounds/") == linkto ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700503 strstr(linkto, "/data/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800504 strstr(linkto, "/system/media/") == linkto) {
505 result.append(" ");
506 result.append(buffer);
507 result.append(" -> ");
508 result.append(linkto);
509 result.append("\n");
510 }
511 }
512 } else {
513 result.append(" unexpected type for ");
514 result.append(buffer);
515 result.append("\n");
516 }
517 }
518 }
519 }
520 closedir(d);
521 } else {
522 result.append("couldn't open ");
523 result.append(buffer);
524 result.append("\n");
525 }
526
Marco Nelissenf09611f2015-02-13 14:12:42 -0800527 gLooperRoster.dump(fd, args);
528
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800529 bool dumpMem = false;
Andy Hung53541292016-04-13 16:48:51 -0700530 bool unreachableMemory = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800531 for (size_t i = 0; i < args.size(); i++) {
532 if (args[i] == String16("-m")) {
533 dumpMem = true;
Andy Hung53541292016-04-13 16:48:51 -0700534 } else if (args[i] == String16("--unreachable")) {
535 unreachableMemory = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800536 }
537 }
538 if (dumpMem) {
Andy Hung07b745e2016-05-23 16:21:07 -0700539 result.append("\nDumping memory:\n");
540 std::string s = dumpMemoryAddresses(100 /* limit */);
541 result.append(s.c_str(), s.size());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800542 }
Andy Hung53541292016-04-13 16:48:51 -0700543 if (unreachableMemory) {
544 result.append("\nDumping unreachable memory:\n");
545 // TODO - should limit be an argument parameter?
546 std::string s = GetUnreachableMemoryString(true /* contents */, 10000 /* limit */);
547 result.append(s.c_str(), s.size());
548 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800549 }
550 write(fd, result.string(), result.size());
551 return NO_ERROR;
552}
553
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -0700554void MediaPlayerService::removeClient(const wp<Client>& client)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800555{
556 Mutex::Autolock lock(mLock);
557 mClients.remove(client);
558}
559
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700560MediaPlayerService::Client::Client(
561 const sp<MediaPlayerService>& service, pid_t pid,
562 int32_t connId, const sp<IMediaPlayerClient>& client,
Glenn Kastend848eb42016-03-08 13:42:11 -0800563 audio_session_t audioSessionId, uid_t uid)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800564{
Steve Block3856b092011-10-20 11:56:00 +0100565 ALOGV("Client(%d) constructor", connId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800566 mPid = pid;
567 mConnId = connId;
568 mService = service;
569 mClient = client;
570 mLoop = false;
571 mStatus = NO_INIT;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700572 mAudioSessionId = audioSessionId;
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700573 mUID = uid;
John Grossmanc795b642012-02-22 15:38:35 -0800574 mRetransmitEndpointValid = false;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700575 mAudioAttributes = NULL;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700576
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800577#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000578 ALOGD("create Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800579 mAntagonizer = new Antagonizer(notify, this);
580#endif
581}
582
583MediaPlayerService::Client::~Client()
584{
Steve Block3856b092011-10-20 11:56:00 +0100585 ALOGV("Client(%d) destructor pid = %d", mConnId, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800586 mAudioOutput.clear();
587 wp<Client> client(this);
588 disconnect();
589 mService->removeClient(client);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700590 if (mAudioAttributes != NULL) {
591 free(mAudioAttributes);
592 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800593}
594
595void MediaPlayerService::Client::disconnect()
596{
Steve Block3856b092011-10-20 11:56:00 +0100597 ALOGV("disconnect(%d) from pid %d", mConnId, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800598 // grab local reference and clear main reference to prevent future
599 // access to object
600 sp<MediaPlayerBase> p;
601 {
602 Mutex::Autolock l(mLock);
603 p = mPlayer;
beanzdcfefde2012-11-05 09:51:43 +0800604 mClient.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800605 }
Andreas Huber20111aa2009-07-14 16:56:47 -0700606
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800607 mPlayer.clear();
608
609 // clear the notification to prevent callbacks to dead client
610 // and reset the player. We assume the player will serialize
611 // access to itself if necessary.
612 if (p != 0) {
613 p->setNotifyCallback(0, 0);
614#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000615 ALOGD("kill Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800616 mAntagonizer->kill();
617#endif
618 p->reset();
619 }
620
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700621 disconnectNativeWindow();
622
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800623 IPCThreadState::self()->flushCommands();
624}
625
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800626sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
627{
628 // determine if we have the right player type
629 sp<MediaPlayerBase> p = mPlayer;
630 if ((p != NULL) && (p->playerType() != playerType)) {
Steve Block3856b092011-10-20 11:56:00 +0100631 ALOGV("delete player");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800632 p.clear();
633 }
634 if (p == NULL) {
Ronghua Wu68845c12015-07-21 09:50:48 -0700635 p = MediaPlayerFactory::createPlayer(playerType, this, notify, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800636 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700637
Jason Simmonsdb29e522011-08-12 13:46:55 -0700638 if (p != NULL) {
639 p->setUID(mUID);
640 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700641
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800642 return p;
643}
644
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700645MediaPlayerService::Client::ServiceDeathNotifier::ServiceDeathNotifier(
646 const sp<IBinder>& service,
647 const sp<MediaPlayerBase>& listener,
648 int which) {
649 mService = service;
650 mListener = listener;
651 mWhich = which;
652}
653
654MediaPlayerService::Client::ServiceDeathNotifier::~ServiceDeathNotifier() {
655 mService->unlinkToDeath(this);
656}
657
658void MediaPlayerService::Client::ServiceDeathNotifier::binderDied(const wp<IBinder>& /*who*/) {
659 sp<MediaPlayerBase> listener = mListener.promote();
660 if (listener != NULL) {
661 listener->sendEvent(MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED, mWhich);
662 } else {
663 ALOGW("listener for process %d death is gone", mWhich);
664 }
665}
666
John Grossmanc795b642012-02-22 15:38:35 -0800667sp<MediaPlayerBase> MediaPlayerService::Client::setDataSource_pre(
668 player_type playerType)
669{
670 ALOGV("player type = %d", playerType);
671
672 // create the right type of player
673 sp<MediaPlayerBase> p = createPlayer(playerType);
674 if (p == NULL) {
675 return p;
676 }
677
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700678 sp<IServiceManager> sm = defaultServiceManager();
679 sp<IBinder> binder = sm->getService(String16("media.extractor"));
680 mExtractorDeathListener = new ServiceDeathNotifier(binder, p, MEDIAEXTRACTOR_PROCESS_DEATH);
681 binder->linkToDeath(mExtractorDeathListener);
682
683 binder = sm->getService(String16("media.codec"));
684 mCodecDeathListener = new ServiceDeathNotifier(binder, p, MEDIACODEC_PROCESS_DEATH);
685 binder->linkToDeath(mCodecDeathListener);
686
John Grossmanc795b642012-02-22 15:38:35 -0800687 if (!p->hardwareOutput()) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -0700688 Mutex::Autolock l(mLock);
Marco Nelissend457c972014-02-11 08:47:07 -0800689 mAudioOutput = new AudioOutput(mAudioSessionId, IPCThreadState::self()->getCallingUid(),
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700690 mPid, mAudioAttributes);
John Grossmanc795b642012-02-22 15:38:35 -0800691 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
692 }
693
694 return p;
695}
696
697void MediaPlayerService::Client::setDataSource_post(
698 const sp<MediaPlayerBase>& p,
699 status_t status)
700{
701 ALOGV(" setDataSource");
702 mStatus = status;
703 if (mStatus != OK) {
704 ALOGE(" error: %d", mStatus);
705 return;
706 }
707
708 // Set the re-transmission endpoint if one was chosen.
709 if (mRetransmitEndpointValid) {
710 mStatus = p->setRetransmitEndpoint(&mRetransmitEndpoint);
711 if (mStatus != NO_ERROR) {
712 ALOGE("setRetransmitEndpoint error: %d", mStatus);
713 }
714 }
715
716 if (mStatus == OK) {
717 mPlayer = p;
718 }
719}
720
Andreas Huber2db84552010-01-28 11:19:57 -0800721status_t MediaPlayerService::Client::setDataSource(
Andreas Huber1b86fe02014-01-29 11:13:26 -0800722 const sp<IMediaHTTPService> &httpService,
723 const char *url,
724 const KeyedVector<String8, String8> *headers)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800725{
Steve Block3856b092011-10-20 11:56:00 +0100726 ALOGV("setDataSource(%s)", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800727 if (url == NULL)
728 return UNKNOWN_ERROR;
729
Dave Burked681bbb2011-08-30 14:39:17 +0100730 if ((strncmp(url, "http://", 7) == 0) ||
731 (strncmp(url, "https://", 8) == 0) ||
732 (strncmp(url, "rtsp://", 7) == 0)) {
733 if (!checkPermission("android.permission.INTERNET")) {
734 return PERMISSION_DENIED;
735 }
736 }
737
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800738 if (strncmp(url, "content://", 10) == 0) {
739 // get a filedescriptor for the content Uri and
740 // pass it to the setDataSource(fd) method
741
742 String16 url16(url);
743 int fd = android::openContentProviderFile(url16);
744 if (fd < 0)
745 {
Steve Block29357bc2012-01-06 19:20:56 +0000746 ALOGE("Couldn't open fd for %s", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800747 return UNKNOWN_ERROR;
748 }
749 setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
750 close(fd);
751 return mStatus;
752 } else {
John Grossman44a7e422012-06-21 17:29:24 -0700753 player_type playerType = MediaPlayerFactory::getPlayerType(this, url);
John Grossmanc795b642012-02-22 15:38:35 -0800754 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
755 if (p == NULL) {
756 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800757 }
758
Andreas Huber1b86fe02014-01-29 11:13:26 -0800759 setDataSource_post(p, p->setDataSource(httpService, url, headers));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800760 return mStatus;
761 }
762}
763
764status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
765{
Marco Nelissen83b0fd92015-09-16 13:48:07 -0700766 ALOGV("setDataSource fd=%d (%s), offset=%lld, length=%lld",
767 fd, nameForFd(fd).c_str(), (long long) offset, (long long) length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800768 struct stat sb;
769 int ret = fstat(fd, &sb);
770 if (ret != 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000771 ALOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800772 return UNKNOWN_ERROR;
773 }
774
Andy Hung833b4752016-04-04 17:15:48 -0700775 ALOGV("st_dev = %llu", static_cast<unsigned long long>(sb.st_dev));
Steve Block3856b092011-10-20 11:56:00 +0100776 ALOGV("st_mode = %u", sb.st_mode);
Mark Salyzyn77342f72014-06-18 16:31:32 -0700777 ALOGV("st_uid = %lu", static_cast<unsigned long>(sb.st_uid));
778 ALOGV("st_gid = %lu", static_cast<unsigned long>(sb.st_gid));
Andy Hung833b4752016-04-04 17:15:48 -0700779 ALOGV("st_size = %llu", static_cast<unsigned long long>(sb.st_size));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800780
781 if (offset >= sb.st_size) {
Steve Block29357bc2012-01-06 19:20:56 +0000782 ALOGE("offset error");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800783 return UNKNOWN_ERROR;
784 }
785 if (offset + length > sb.st_size) {
786 length = sb.st_size - offset;
Andy Hung833b4752016-04-04 17:15:48 -0700787 ALOGV("calculated length = %lld", (long long)length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800788 }
789
John Grossman44a7e422012-06-21 17:29:24 -0700790 player_type playerType = MediaPlayerFactory::getPlayerType(this,
791 fd,
792 offset,
793 length);
John Grossmanc795b642012-02-22 15:38:35 -0800794 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
795 if (p == NULL) {
796 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800797 }
798
799 // now set data source
John Grossmanc795b642012-02-22 15:38:35 -0800800 setDataSource_post(p, p->setDataSource(fd, offset, length));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800801 return mStatus;
802}
803
Andreas Hubere2b10282010-11-23 11:41:34 -0800804status_t MediaPlayerService::Client::setDataSource(
805 const sp<IStreamSource> &source) {
806 // create the right type of player
John Grossman44a7e422012-06-21 17:29:24 -0700807 player_type playerType = MediaPlayerFactory::getPlayerType(this, source);
John Grossmanc795b642012-02-22 15:38:35 -0800808 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
Andreas Hubere2b10282010-11-23 11:41:34 -0800809 if (p == NULL) {
810 return NO_INIT;
811 }
812
Andreas Hubere2b10282010-11-23 11:41:34 -0800813 // now set data source
John Grossmanc795b642012-02-22 15:38:35 -0800814 setDataSource_post(p, p->setDataSource(source));
Andreas Hubere2b10282010-11-23 11:41:34 -0800815 return mStatus;
816}
817
Chris Watkins99f31602015-03-20 13:06:33 -0700818status_t MediaPlayerService::Client::setDataSource(
819 const sp<IDataSource> &source) {
820 sp<DataSource> dataSource = DataSource::CreateFromIDataSource(source);
821 player_type playerType = MediaPlayerFactory::getPlayerType(this, dataSource);
822 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
823 if (p == NULL) {
824 return NO_INIT;
825 }
826 // now set data source
827 setDataSource_post(p, p->setDataSource(dataSource));
828 return mStatus;
829}
830
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700831void MediaPlayerService::Client::disconnectNativeWindow() {
832 if (mConnectedWindow != NULL) {
833 status_t err = native_window_api_disconnect(mConnectedWindow.get(),
834 NATIVE_WINDOW_API_MEDIA);
835
836 if (err != OK) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000837 ALOGW("native_window_api_disconnect returned an error: %s (%d)",
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700838 strerror(-err), err);
839 }
840 }
841 mConnectedWindow.clear();
842}
843
Glenn Kasten11731182011-02-08 17:26:17 -0800844status_t MediaPlayerService::Client::setVideoSurfaceTexture(
Andy McFadden484566c2012-12-18 09:46:54 -0800845 const sp<IGraphicBufferProducer>& bufferProducer)
Glenn Kasten11731182011-02-08 17:26:17 -0800846{
Andy McFadden484566c2012-12-18 09:46:54 -0800847 ALOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, bufferProducer.get());
Glenn Kasten11731182011-02-08 17:26:17 -0800848 sp<MediaPlayerBase> p = getPlayer();
849 if (p == 0) return UNKNOWN_ERROR;
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700850
Marco Nelissenf8880202014-11-14 07:58:25 -0800851 sp<IBinder> binder(IInterface::asBinder(bufferProducer));
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700852 if (mConnectedWindowBinder == binder) {
853 return OK;
854 }
855
856 sp<ANativeWindow> anw;
Andy McFadden484566c2012-12-18 09:46:54 -0800857 if (bufferProducer != NULL) {
Marco Nelissenee08f7e2013-09-16 13:30:01 -0700858 anw = new Surface(bufferProducer, true /* controlledByApp */);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700859 status_t err = native_window_api_connect(anw.get(),
860 NATIVE_WINDOW_API_MEDIA);
861
862 if (err != OK) {
Steve Block29357bc2012-01-06 19:20:56 +0000863 ALOGE("setVideoSurfaceTexture failed: %d", err);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700864 // Note that we must do the reset before disconnecting from the ANW.
865 // Otherwise queue/dequeue calls could be made on the disconnected
866 // ANW, which may result in errors.
867 reset();
868
869 disconnectNativeWindow();
870
871 return err;
872 }
873 }
874
Andy McFadden484566c2012-12-18 09:46:54 -0800875 // Note that we must set the player's new GraphicBufferProducer before
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700876 // disconnecting the old one. Otherwise queue/dequeue calls could be made
877 // on the disconnected ANW, which may result in errors.
Andy McFadden484566c2012-12-18 09:46:54 -0800878 status_t err = p->setVideoSurfaceTexture(bufferProducer);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700879
880 disconnectNativeWindow();
881
882 mConnectedWindow = anw;
883
884 if (err == OK) {
885 mConnectedWindowBinder = binder;
886 } else {
887 disconnectNativeWindow();
888 }
889
890 return err;
Glenn Kasten11731182011-02-08 17:26:17 -0800891}
892
Nicolas Catania1d187f12009-05-12 23:25:55 -0700893status_t MediaPlayerService::Client::invoke(const Parcel& request,
894 Parcel *reply)
895{
896 sp<MediaPlayerBase> p = getPlayer();
897 if (p == NULL) return UNKNOWN_ERROR;
898 return p->invoke(request, reply);
899}
900
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700901// This call doesn't need to access the native player.
902status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
903{
904 status_t status;
nikoa64c8c72009-07-20 15:07:26 -0700905 media::Metadata::Filter allow, drop;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700906
Nicolas Catania48290382009-07-10 13:53:06 -0700907 if (unmarshallFilter(filter, &allow, &status) &&
908 unmarshallFilter(filter, &drop, &status)) {
909 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700910
911 mMetadataAllow = allow;
912 mMetadataDrop = drop;
913 }
914 return status;
915}
916
Nicolas Catania48290382009-07-10 13:53:06 -0700917status_t MediaPlayerService::Client::getMetadata(
Mark Salyzyn77342f72014-06-18 16:31:32 -0700918 bool update_only, bool /*apply_filter*/, Parcel *reply)
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700919{
nikoa64c8c72009-07-20 15:07:26 -0700920 sp<MediaPlayerBase> player = getPlayer();
921 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania48290382009-07-10 13:53:06 -0700922
nikod608a812009-07-16 16:39:53 -0700923 status_t status;
924 // Placeholder for the return code, updated by the caller.
925 reply->writeInt32(-1);
926
nikoa64c8c72009-07-20 15:07:26 -0700927 media::Metadata::Filter ids;
Nicolas Catania48290382009-07-10 13:53:06 -0700928
929 // We don't block notifications while we fetch the data. We clear
930 // mMetadataUpdated first so we don't lose notifications happening
931 // during the rest of this call.
932 {
933 Mutex::Autolock lock(mLock);
934 if (update_only) {
nikod608a812009-07-16 16:39:53 -0700935 ids = mMetadataUpdated;
Nicolas Catania48290382009-07-10 13:53:06 -0700936 }
937 mMetadataUpdated.clear();
938 }
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700939
nikoa64c8c72009-07-20 15:07:26 -0700940 media::Metadata metadata(reply);
Nicolas Catania48290382009-07-10 13:53:06 -0700941
nikoa64c8c72009-07-20 15:07:26 -0700942 metadata.appendHeader();
943 status = player->getMetadata(ids, reply);
nikod608a812009-07-16 16:39:53 -0700944
945 if (status != OK) {
nikoa64c8c72009-07-20 15:07:26 -0700946 metadata.resetParcel();
Steve Block29357bc2012-01-06 19:20:56 +0000947 ALOGE("getMetadata failed %d", status);
nikod608a812009-07-16 16:39:53 -0700948 return status;
949 }
950
951 // FIXME: Implement filtering on the result. Not critical since
952 // filtering takes place on the update notifications already. This
953 // would be when all the metadata are fetch and a filter is set.
954
nikod608a812009-07-16 16:39:53 -0700955 // Everything is fine, update the metadata length.
nikoa64c8c72009-07-20 15:07:26 -0700956 metadata.updateLength();
nikod608a812009-07-16 16:39:53 -0700957 return OK;
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700958}
959
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800960status_t MediaPlayerService::Client::prepareAsync()
961{
Steve Block3856b092011-10-20 11:56:00 +0100962 ALOGV("[%d] prepareAsync", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800963 sp<MediaPlayerBase> p = getPlayer();
964 if (p == 0) return UNKNOWN_ERROR;
965 status_t ret = p->prepareAsync();
966#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000967 ALOGD("start Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800968 if (ret == NO_ERROR) mAntagonizer->start();
969#endif
970 return ret;
971}
972
973status_t MediaPlayerService::Client::start()
974{
Steve Block3856b092011-10-20 11:56:00 +0100975 ALOGV("[%d] start", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800976 sp<MediaPlayerBase> p = getPlayer();
977 if (p == 0) return UNKNOWN_ERROR;
978 p->setLooping(mLoop);
979 return p->start();
980}
981
982status_t MediaPlayerService::Client::stop()
983{
Steve Block3856b092011-10-20 11:56:00 +0100984 ALOGV("[%d] stop", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800985 sp<MediaPlayerBase> p = getPlayer();
986 if (p == 0) return UNKNOWN_ERROR;
987 return p->stop();
988}
989
990status_t MediaPlayerService::Client::pause()
991{
Steve Block3856b092011-10-20 11:56:00 +0100992 ALOGV("[%d] pause", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800993 sp<MediaPlayerBase> p = getPlayer();
994 if (p == 0) return UNKNOWN_ERROR;
995 return p->pause();
996}
997
998status_t MediaPlayerService::Client::isPlaying(bool* state)
999{
1000 *state = false;
1001 sp<MediaPlayerBase> p = getPlayer();
1002 if (p == 0) return UNKNOWN_ERROR;
1003 *state = p->isPlaying();
Steve Block3856b092011-10-20 11:56:00 +01001004 ALOGV("[%d] isPlaying: %d", mConnId, *state);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001005 return NO_ERROR;
1006}
1007
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001008status_t MediaPlayerService::Client::setPlaybackSettings(const AudioPlaybackRate& rate)
Wei Jia98160162015-02-04 17:01:11 -08001009{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001010 ALOGV("[%d] setPlaybackSettings(%f, %f, %d, %d)",
1011 mConnId, rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Wei Jia98160162015-02-04 17:01:11 -08001012 sp<MediaPlayerBase> p = getPlayer();
1013 if (p == 0) return UNKNOWN_ERROR;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001014 return p->setPlaybackSettings(rate);
1015}
1016
1017status_t MediaPlayerService::Client::getPlaybackSettings(AudioPlaybackRate* rate /* nonnull */)
1018{
1019 sp<MediaPlayerBase> p = getPlayer();
1020 if (p == 0) return UNKNOWN_ERROR;
1021 status_t ret = p->getPlaybackSettings(rate);
1022 if (ret == NO_ERROR) {
1023 ALOGV("[%d] getPlaybackSettings(%f, %f, %d, %d)",
1024 mConnId, rate->mSpeed, rate->mPitch, rate->mFallbackMode, rate->mStretchMode);
1025 } else {
1026 ALOGV("[%d] getPlaybackSettings returned %d", mConnId, ret);
1027 }
1028 return ret;
1029}
1030
1031status_t MediaPlayerService::Client::setSyncSettings(
1032 const AVSyncSettings& sync, float videoFpsHint)
1033{
1034 ALOGV("[%d] setSyncSettings(%u, %u, %f, %f)",
1035 mConnId, sync.mSource, sync.mAudioAdjustMode, sync.mTolerance, videoFpsHint);
1036 sp<MediaPlayerBase> p = getPlayer();
1037 if (p == 0) return UNKNOWN_ERROR;
1038 return p->setSyncSettings(sync, videoFpsHint);
1039}
1040
1041status_t MediaPlayerService::Client::getSyncSettings(
1042 AVSyncSettings* sync /* nonnull */, float* videoFps /* nonnull */)
1043{
1044 sp<MediaPlayerBase> p = getPlayer();
1045 if (p == 0) return UNKNOWN_ERROR;
1046 status_t ret = p->getSyncSettings(sync, videoFps);
1047 if (ret == NO_ERROR) {
1048 ALOGV("[%d] getSyncSettings(%u, %u, %f, %f)",
1049 mConnId, sync->mSource, sync->mAudioAdjustMode, sync->mTolerance, *videoFps);
1050 } else {
1051 ALOGV("[%d] getSyncSettings returned %d", mConnId, ret);
1052 }
1053 return ret;
Wei Jia98160162015-02-04 17:01:11 -08001054}
1055
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001056status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
1057{
Steve Block3856b092011-10-20 11:56:00 +01001058 ALOGV("getCurrentPosition");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001059 sp<MediaPlayerBase> p = getPlayer();
1060 if (p == 0) return UNKNOWN_ERROR;
1061 status_t ret = p->getCurrentPosition(msec);
1062 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001063 ALOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001064 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001065 ALOGE("getCurrentPosition returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001066 }
1067 return ret;
1068}
1069
1070status_t MediaPlayerService::Client::getDuration(int *msec)
1071{
Steve Block3856b092011-10-20 11:56:00 +01001072 ALOGV("getDuration");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001073 sp<MediaPlayerBase> p = getPlayer();
1074 if (p == 0) return UNKNOWN_ERROR;
1075 status_t ret = p->getDuration(msec);
1076 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001077 ALOGV("[%d] getDuration = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001078 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001079 ALOGE("getDuration returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001080 }
1081 return ret;
1082}
1083
Marco Nelissen6b74d672012-02-28 16:07:44 -08001084status_t MediaPlayerService::Client::setNextPlayer(const sp<IMediaPlayer>& player) {
1085 ALOGV("setNextPlayer");
1086 Mutex::Autolock l(mLock);
1087 sp<Client> c = static_cast<Client*>(player.get());
1088 mNextClient = c;
John Grossman5f7e55e2012-08-24 14:47:25 -07001089
1090 if (c != NULL) {
1091 if (mAudioOutput != NULL) {
1092 mAudioOutput->setNextOutput(c->mAudioOutput);
1093 } else if ((mPlayer != NULL) && !mPlayer->hardwareOutput()) {
1094 ALOGE("no current audio output");
1095 }
1096
1097 if ((mPlayer != NULL) && (mNextClient->getPlayer() != NULL)) {
1098 mPlayer->setNextPlayer(mNextClient->getPlayer());
1099 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001100 }
John Grossman5f7e55e2012-08-24 14:47:25 -07001101
Marco Nelissen6b74d672012-02-28 16:07:44 -08001102 return OK;
1103}
1104
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001105status_t MediaPlayerService::Client::seekTo(int msec)
1106{
Steve Block3856b092011-10-20 11:56:00 +01001107 ALOGV("[%d] seekTo(%d)", mConnId, msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001108 sp<MediaPlayerBase> p = getPlayer();
1109 if (p == 0) return UNKNOWN_ERROR;
1110 return p->seekTo(msec);
1111}
1112
1113status_t MediaPlayerService::Client::reset()
1114{
Steve Block3856b092011-10-20 11:56:00 +01001115 ALOGV("[%d] reset", mConnId);
John Grossmanc795b642012-02-22 15:38:35 -08001116 mRetransmitEndpointValid = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001117 sp<MediaPlayerBase> p = getPlayer();
1118 if (p == 0) return UNKNOWN_ERROR;
1119 return p->reset();
1120}
1121
Glenn Kastenfff6d712012-01-12 16:38:12 -08001122status_t MediaPlayerService::Client::setAudioStreamType(audio_stream_type_t type)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001123{
Steve Block3856b092011-10-20 11:56:00 +01001124 ALOGV("[%d] setAudioStreamType(%d)", mConnId, type);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001125 // TODO: for hardware output, call player instead
1126 Mutex::Autolock l(mLock);
1127 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1128 return NO_ERROR;
1129}
1130
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001131status_t MediaPlayerService::Client::setAudioAttributes_l(const Parcel &parcel)
1132{
1133 if (mAudioAttributes != NULL) { free(mAudioAttributes); }
1134 mAudioAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001135 if (mAudioAttributes == NULL) {
1136 return NO_MEMORY;
1137 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001138 unmarshallAudioAttributes(parcel, mAudioAttributes);
1139
1140 ALOGV("setAudioAttributes_l() usage=%d content=%d flags=0x%x tags=%s",
1141 mAudioAttributes->usage, mAudioAttributes->content_type, mAudioAttributes->flags,
1142 mAudioAttributes->tags);
1143
1144 if (mAudioOutput != 0) {
1145 mAudioOutput->setAudioAttributes(mAudioAttributes);
1146 }
1147 return NO_ERROR;
1148}
1149
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001150status_t MediaPlayerService::Client::setLooping(int loop)
1151{
Steve Block3856b092011-10-20 11:56:00 +01001152 ALOGV("[%d] setLooping(%d)", mConnId, loop);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001153 mLoop = loop;
1154 sp<MediaPlayerBase> p = getPlayer();
1155 if (p != 0) return p->setLooping(loop);
1156 return NO_ERROR;
1157}
1158
1159status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1160{
Steve Block3856b092011-10-20 11:56:00 +01001161 ALOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
John Grossman761defc2012-02-09 15:09:05 -08001162
1163 // for hardware output, call player instead
1164 sp<MediaPlayerBase> p = getPlayer();
1165 {
1166 Mutex::Autolock l(mLock);
1167 if (p != 0 && p->hardwareOutput()) {
1168 MediaPlayerHWInterface* hwp =
1169 reinterpret_cast<MediaPlayerHWInterface*>(p.get());
1170 return hwp->setVolume(leftVolume, rightVolume);
1171 } else {
1172 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1173 return NO_ERROR;
1174 }
1175 }
1176
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001177 return NO_ERROR;
1178}
1179
Eric Laurent2beeb502010-07-16 07:43:46 -07001180status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1181{
Steve Block3856b092011-10-20 11:56:00 +01001182 ALOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
Eric Laurent2beeb502010-07-16 07:43:46 -07001183 Mutex::Autolock l(mLock);
1184 if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1185 return NO_ERROR;
1186}
1187
1188status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1189{
Steve Block3856b092011-10-20 11:56:00 +01001190 ALOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
Eric Laurent2beeb502010-07-16 07:43:46 -07001191 Mutex::Autolock l(mLock);
1192 if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1193 return NO_ERROR;
1194}
Nicolas Catania48290382009-07-10 13:53:06 -07001195
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001196status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
Steve Block3856b092011-10-20 11:56:00 +01001197 ALOGV("[%d] setParameter(%d)", mConnId, key);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001198 switch (key) {
1199 case KEY_PARAMETER_AUDIO_ATTRIBUTES:
1200 {
1201 Mutex::Autolock l(mLock);
1202 return setAudioAttributes_l(request);
1203 }
1204 default:
1205 sp<MediaPlayerBase> p = getPlayer();
1206 if (p == 0) { return UNKNOWN_ERROR; }
1207 return p->setParameter(key, request);
1208 }
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001209}
1210
1211status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
Steve Block3856b092011-10-20 11:56:00 +01001212 ALOGV("[%d] getParameter(%d)", mConnId, key);
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001213 sp<MediaPlayerBase> p = getPlayer();
1214 if (p == 0) return UNKNOWN_ERROR;
1215 return p->getParameter(key, reply);
1216}
1217
John Grossmanc795b642012-02-22 15:38:35 -08001218status_t MediaPlayerService::Client::setRetransmitEndpoint(
1219 const struct sockaddr_in* endpoint) {
1220
1221 if (NULL != endpoint) {
1222 uint32_t a = ntohl(endpoint->sin_addr.s_addr);
1223 uint16_t p = ntohs(endpoint->sin_port);
1224 ALOGV("[%d] setRetransmitEndpoint(%u.%u.%u.%u:%hu)", mConnId,
1225 (a >> 24), (a >> 16) & 0xFF, (a >> 8) & 0xFF, (a & 0xFF), p);
1226 } else {
1227 ALOGV("[%d] setRetransmitEndpoint = <none>", mConnId);
1228 }
1229
1230 sp<MediaPlayerBase> p = getPlayer();
1231
1232 // Right now, the only valid time to set a retransmit endpoint is before
1233 // player selection has been made (since the presence or absence of a
1234 // retransmit endpoint is going to determine which player is selected during
1235 // setDataSource).
1236 if (p != 0) return INVALID_OPERATION;
1237
1238 if (NULL != endpoint) {
1239 mRetransmitEndpoint = *endpoint;
1240 mRetransmitEndpointValid = true;
1241 } else {
1242 mRetransmitEndpointValid = false;
1243 }
1244
1245 return NO_ERROR;
1246}
1247
John Grossman44a7e422012-06-21 17:29:24 -07001248status_t MediaPlayerService::Client::getRetransmitEndpoint(
1249 struct sockaddr_in* endpoint)
1250{
1251 if (NULL == endpoint)
1252 return BAD_VALUE;
1253
1254 sp<MediaPlayerBase> p = getPlayer();
1255
1256 if (p != NULL)
1257 return p->getRetransmitEndpoint(endpoint);
1258
1259 if (!mRetransmitEndpointValid)
1260 return NO_INIT;
1261
1262 *endpoint = mRetransmitEndpoint;
1263
1264 return NO_ERROR;
1265}
1266
Gloria Wangb483c472011-04-11 17:23:27 -07001267void MediaPlayerService::Client::notify(
1268 void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001269{
1270 Client* client = static_cast<Client*>(cookie);
James Dongb8a98252012-08-26 16:13:03 -07001271 if (client == NULL) {
1272 return;
1273 }
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001274
James Dongb8a98252012-08-26 16:13:03 -07001275 sp<IMediaPlayerClient> c;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001276 {
1277 Mutex::Autolock l(client->mLock);
James Dongb8a98252012-08-26 16:13:03 -07001278 c = client->mClient;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001279 if (msg == MEDIA_PLAYBACK_COMPLETE && client->mNextClient != NULL) {
John Grossmancb0b7552012-08-23 17:47:31 -07001280 if (client->mAudioOutput != NULL)
1281 client->mAudioOutput->switchToNextOutput();
Marco Nelissen6b74d672012-02-28 16:07:44 -08001282 client->mNextClient->start();
Wei Jia2afac0c2016-01-07 12:13:07 -08001283 if (client->mNextClient->mClient != NULL) {
1284 client->mNextClient->mClient->notify(
1285 MEDIA_INFO, MEDIA_INFO_STARTED_AS_NEXT, 0, obj);
1286 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001287 }
1288 }
1289
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001290 if (MEDIA_INFO == msg &&
Nicolas Catania48290382009-07-10 13:53:06 -07001291 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikoa64c8c72009-07-20 15:07:26 -07001292 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania48290382009-07-10 13:53:06 -07001293
1294 if(client->shouldDropMetadata(metadata_type)) {
1295 return;
1296 }
1297
1298 // Update the list of metadata that have changed. getMetadata
1299 // also access mMetadataUpdated and clears it.
1300 client->addNewMetadataUpdate(metadata_type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001301 }
James Dongb8a98252012-08-26 16:13:03 -07001302
1303 if (c != NULL) {
1304 ALOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
1305 c->notify(msg, ext1, ext2, obj);
1306 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001307}
1308
Nicolas Catania48290382009-07-10 13:53:06 -07001309
nikoa64c8c72009-07-20 15:07:26 -07001310bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001311{
Nicolas Catania48290382009-07-10 13:53:06 -07001312 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001313
Nicolas Catania48290382009-07-10 13:53:06 -07001314 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001315 return true;
1316 }
1317
Nicolas Catania48290382009-07-10 13:53:06 -07001318 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001319 return false;
Nicolas Catania48290382009-07-10 13:53:06 -07001320 } else {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001321 return true;
1322 }
1323}
1324
Nicolas Catania48290382009-07-10 13:53:06 -07001325
nikoa64c8c72009-07-20 15:07:26 -07001326void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania48290382009-07-10 13:53:06 -07001327 Mutex::Autolock lock(mLock);
1328 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1329 mMetadataUpdated.add(metadata_type);
1330 }
1331}
1332
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001333#if CALLBACK_ANTAGONIZER
1334const int Antagonizer::interval = 10000; // 10 msecs
1335
1336Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1337 mExit(false), mActive(false), mClient(client), mCb(cb)
1338{
1339 createThread(callbackThread, this);
1340}
1341
1342void Antagonizer::kill()
1343{
1344 Mutex::Autolock _l(mLock);
1345 mActive = false;
1346 mExit = true;
1347 mCondition.wait(mLock);
1348}
1349
1350int Antagonizer::callbackThread(void* user)
1351{
Steve Blockb8a80522011-12-20 16:23:08 +00001352 ALOGD("Antagonizer started");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001353 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1354 while (!p->mExit) {
1355 if (p->mActive) {
Steve Block3856b092011-10-20 11:56:00 +01001356 ALOGV("send event");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001357 p->mCb(p->mClient, 0, 0, 0);
1358 }
1359 usleep(interval);
1360 }
1361 Mutex::Autolock _l(p->mLock);
1362 p->mCondition.signal();
Steve Blockb8a80522011-12-20 16:23:08 +00001363 ALOGD("Antagonizer stopped");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001364 return 0;
1365}
1366#endif
1367
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001368#undef LOG_TAG
1369#define LOG_TAG "AudioSink"
Glenn Kastend848eb42016-03-08 13:42:11 -08001370MediaPlayerService::AudioOutput::AudioOutput(audio_session_t sessionId, int uid, int pid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001371 const audio_attributes_t* attr)
Andreas Huber20111aa2009-07-14 16:56:47 -07001372 : mCallback(NULL),
Eric Laurenta514bdb2010-06-21 09:27:30 -07001373 mCallbackCookie(NULL),
Marco Nelissen6b74d672012-02-28 16:07:44 -08001374 mCallbackData(NULL),
Andy Hungd1c74342015-07-07 16:54:23 -07001375 mStreamType(AUDIO_STREAM_MUSIC),
Andy Hungd1c74342015-07-07 16:54:23 -07001376 mLeftVolume(1.0),
1377 mRightVolume(1.0),
1378 mPlaybackRate(AUDIO_PLAYBACK_RATE_DEFAULT),
1379 mSampleRateHz(0),
1380 mMsecsPerFrame(0),
1381 mFrameSize(0),
Eric Laurent1948eb32012-04-13 16:50:19 -07001382 mSessionId(sessionId),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001383 mUid(uid),
Marco Nelissend457c972014-02-11 08:47:07 -08001384 mPid(pid),
Andy Hungd1c74342015-07-07 16:54:23 -07001385 mSendLevel(0.0),
1386 mAuxEffectId(0),
1387 mFlags(AUDIO_OUTPUT_FLAG_NONE)
1388{
Steve Block3856b092011-10-20 11:56:00 +01001389 ALOGV("AudioOutput(%d)", sessionId);
Eric Laurent43562692015-07-15 16:49:07 -07001390 if (attr != NULL) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001391 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1392 if (mAttributes != NULL) {
1393 memcpy(mAttributes, attr, sizeof(audio_attributes_t));
1394 mStreamType = audio_attributes_to_stream_type(attr);
1395 }
1396 } else {
1397 mAttributes = NULL;
Eric Laurent43562692015-07-15 16:49:07 -07001398 }
1399
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001400 setMinBufferCount();
1401}
1402
1403MediaPlayerService::AudioOutput::~AudioOutput()
1404{
1405 close();
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001406 free(mAttributes);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001407 delete mCallbackData;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001408}
1409
Andy Hungd1c74342015-07-07 16:54:23 -07001410//static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001411void MediaPlayerService::AudioOutput::setMinBufferCount()
1412{
1413 char value[PROPERTY_VALUE_MAX];
1414 if (property_get("ro.kernel.qemu", value, 0)) {
1415 mIsOnEmulator = true;
1416 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1417 }
1418}
1419
Andy Hungd1c74342015-07-07 16:54:23 -07001420// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001421bool MediaPlayerService::AudioOutput::isOnEmulator()
1422{
Andy Hungd1c74342015-07-07 16:54:23 -07001423 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001424 return mIsOnEmulator;
1425}
1426
Andy Hungd1c74342015-07-07 16:54:23 -07001427// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001428int MediaPlayerService::AudioOutput::getMinBufferCount()
1429{
Andy Hungd1c74342015-07-07 16:54:23 -07001430 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001431 return mMinBufferCount;
1432}
1433
1434ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1435{
Andy Hungd1c74342015-07-07 16:54:23 -07001436 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001437 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001438 return mTrack->frameCount() * mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001439}
1440
1441ssize_t MediaPlayerService::AudioOutput::frameCount() const
1442{
Andy Hungd1c74342015-07-07 16:54:23 -07001443 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001444 if (mTrack == 0) return NO_INIT;
1445 return mTrack->frameCount();
1446}
1447
1448ssize_t MediaPlayerService::AudioOutput::channelCount() const
1449{
Andy Hungd1c74342015-07-07 16:54:23 -07001450 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001451 if (mTrack == 0) return NO_INIT;
1452 return mTrack->channelCount();
1453}
1454
1455ssize_t MediaPlayerService::AudioOutput::frameSize() const
1456{
Andy Hungd1c74342015-07-07 16:54:23 -07001457 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001458 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001459 return mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001460}
1461
1462uint32_t MediaPlayerService::AudioOutput::latency () const
1463{
Andy Hungd1c74342015-07-07 16:54:23 -07001464 Mutex::Autolock lock(mLock);
Eric Laurentdb354e52012-03-05 17:27:11 -08001465 if (mTrack == 0) return 0;
1466 return mTrack->latency();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001467}
1468
1469float MediaPlayerService::AudioOutput::msecsPerFrame() const
1470{
Andy Hungd1c74342015-07-07 16:54:23 -07001471 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001472 return mMsecsPerFrame;
1473}
1474
Marco Nelissen4110c102012-03-29 09:31:28 -07001475status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position) const
Eric Laurent342e9cf2010-01-19 17:37:09 -08001476{
Andy Hungd1c74342015-07-07 16:54:23 -07001477 Mutex::Autolock lock(mLock);
Eric Laurent342e9cf2010-01-19 17:37:09 -08001478 if (mTrack == 0) return NO_INIT;
1479 return mTrack->getPosition(position);
1480}
1481
Lajos Molnar06ad1522014-08-28 07:27:44 -07001482status_t MediaPlayerService::AudioOutput::getTimestamp(AudioTimestamp &ts) const
1483{
Andy Hungd1c74342015-07-07 16:54:23 -07001484 Mutex::Autolock lock(mLock);
Lajos Molnar06ad1522014-08-28 07:27:44 -07001485 if (mTrack == 0) return NO_INIT;
1486 return mTrack->getTimestamp(ts);
1487}
1488
Wei Jiac4ac8172015-10-21 10:35:48 -07001489// TODO: Remove unnecessary calls to getPlayedOutDurationUs()
1490// as it acquires locks and may query the audio driver.
1491//
1492// Some calls could conceivably retrieve extrapolated data instead of
1493// accessing getTimestamp() or getPosition() every time a data buffer with
1494// a media time is received.
1495//
1496// Calculate duration of played samples if played at normal rate (i.e., 1.0).
1497int64_t MediaPlayerService::AudioOutput::getPlayedOutDurationUs(int64_t nowUs) const
1498{
1499 Mutex::Autolock lock(mLock);
1500 if (mTrack == 0 || mSampleRateHz == 0) {
Wei Jia213f4902015-10-22 08:55:25 -07001501 return 0;
Wei Jiac4ac8172015-10-21 10:35:48 -07001502 }
1503
1504 uint32_t numFramesPlayed;
1505 int64_t numFramesPlayedAt;
1506 AudioTimestamp ts;
1507 static const int64_t kStaleTimestamp100ms = 100000;
1508
1509 status_t res = mTrack->getTimestamp(ts);
1510 if (res == OK) { // case 1: mixing audio tracks and offloaded tracks.
1511 numFramesPlayed = ts.mPosition;
1512 numFramesPlayedAt = ts.mTime.tv_sec * 1000000LL + ts.mTime.tv_nsec / 1000;
1513 const int64_t timestampAge = nowUs - numFramesPlayedAt;
1514 if (timestampAge > kStaleTimestamp100ms) {
1515 // This is an audio FIXME.
1516 // getTimestamp returns a timestamp which may come from audio mixing threads.
1517 // After pausing, the MixerThread may go idle, thus the mTime estimate may
1518 // become stale. Assuming that the MixerThread runs 20ms, with FastMixer at 5ms,
1519 // the max latency should be about 25ms with an average around 12ms (to be verified).
1520 // For safety we use 100ms.
1521 ALOGV("getTimestamp: returned stale timestamp nowUs(%lld) numFramesPlayedAt(%lld)",
1522 (long long)nowUs, (long long)numFramesPlayedAt);
1523 numFramesPlayedAt = nowUs - kStaleTimestamp100ms;
1524 }
1525 //ALOGD("getTimestamp: OK %d %lld", numFramesPlayed, (long long)numFramesPlayedAt);
1526 } else if (res == WOULD_BLOCK) { // case 2: transitory state on start of a new track
1527 numFramesPlayed = 0;
1528 numFramesPlayedAt = nowUs;
1529 //ALOGD("getTimestamp: WOULD_BLOCK %d %lld",
1530 // numFramesPlayed, (long long)numFramesPlayedAt);
1531 } else { // case 3: transitory at new track or audio fast tracks.
1532 res = mTrack->getPosition(&numFramesPlayed);
1533 CHECK_EQ(res, (status_t)OK);
1534 numFramesPlayedAt = nowUs;
1535 numFramesPlayedAt += 1000LL * mTrack->latency() / 2; /* XXX */
1536 //ALOGD("getPosition: %u %lld", numFramesPlayed, (long long)numFramesPlayedAt);
1537 }
1538
1539 // CHECK_EQ(numFramesPlayed & (1 << 31), 0); // can't be negative until 12.4 hrs, test
1540 // TODO: remove the (int32_t) casting below as it may overflow at 12.4 hours.
1541 int64_t durationUs = (int64_t)((int32_t)numFramesPlayed * 1000000LL / mSampleRateHz)
1542 + nowUs - numFramesPlayedAt;
1543 if (durationUs < 0) {
1544 // Occurs when numFramesPlayed position is very small and the following:
1545 // (1) In case 1, the time nowUs is computed before getTimestamp() is called and
1546 // numFramesPlayedAt is greater than nowUs by time more than numFramesPlayed.
1547 // (2) In case 3, using getPosition and adding mAudioSink->latency() to
1548 // numFramesPlayedAt, by a time amount greater than numFramesPlayed.
1549 //
1550 // Both of these are transitory conditions.
1551 ALOGV("getPlayedOutDurationUs: negative duration %lld set to zero", (long long)durationUs);
1552 durationUs = 0;
1553 }
1554 ALOGV("getPlayedOutDurationUs(%lld) nowUs(%lld) frames(%u) framesAt(%lld)",
1555 (long long)durationUs, (long long)nowUs, numFramesPlayed, (long long)numFramesPlayedAt);
1556 return durationUs;
1557}
1558
Marco Nelissen4110c102012-03-29 09:31:28 -07001559status_t MediaPlayerService::AudioOutput::getFramesWritten(uint32_t *frameswritten) const
1560{
Andy Hungd1c74342015-07-07 16:54:23 -07001561 Mutex::Autolock lock(mLock);
Marco Nelissen4110c102012-03-29 09:31:28 -07001562 if (mTrack == 0) return NO_INIT;
Andy Hung2f6e73d2016-04-08 12:12:58 -07001563 ExtendedTimestamp ets;
1564 status_t status = mTrack->getTimestamp(&ets);
1565 if (status == OK || status == WOULD_BLOCK) {
1566 *frameswritten = (uint32_t)ets.mPosition[ExtendedTimestamp::LOCATION_CLIENT];
1567 }
1568 return status;
Marco Nelissen4110c102012-03-29 09:31:28 -07001569}
1570
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001571status_t MediaPlayerService::AudioOutput::setParameters(const String8& keyValuePairs)
1572{
Andy Hungd1c74342015-07-07 16:54:23 -07001573 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001574 if (mTrack == 0) return NO_INIT;
1575 return mTrack->setParameters(keyValuePairs);
1576}
1577
1578String8 MediaPlayerService::AudioOutput::getParameters(const String8& keys)
1579{
Andy Hungd1c74342015-07-07 16:54:23 -07001580 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001581 if (mTrack == 0) return String8::empty();
1582 return mTrack->getParameters(keys);
1583}
1584
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001585void MediaPlayerService::AudioOutput::setAudioAttributes(const audio_attributes_t * attributes) {
Andy Hungd1c74342015-07-07 16:54:23 -07001586 Mutex::Autolock lock(mLock);
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001587 if (attributes == NULL) {
1588 free(mAttributes);
1589 mAttributes = NULL;
1590 } else {
1591 if (mAttributes == NULL) {
1592 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1593 }
1594 memcpy(mAttributes, attributes, sizeof(audio_attributes_t));
Eric Laurent43562692015-07-15 16:49:07 -07001595 mStreamType = audio_attributes_to_stream_type(attributes);
1596 }
1597}
1598
1599void MediaPlayerService::AudioOutput::setAudioStreamType(audio_stream_type_t streamType)
1600{
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001601 Mutex::Autolock lock(mLock);
Eric Laurent43562692015-07-15 16:49:07 -07001602 // do not allow direct stream type modification if attributes have been set
1603 if (mAttributes == NULL) {
1604 mStreamType = streamType;
1605 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001606}
1607
Andy Hungd1c74342015-07-07 16:54:23 -07001608void MediaPlayerService::AudioOutput::deleteRecycledTrack_l()
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001609{
Andy Hungd1c74342015-07-07 16:54:23 -07001610 ALOGV("deleteRecycledTrack_l");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001611 if (mRecycledTrack != 0) {
1612
1613 if (mCallbackData != NULL) {
1614 mCallbackData->setOutput(NULL);
1615 mCallbackData->endTrackSwitch();
1616 }
1617
1618 if ((mRecycledTrack->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) {
Andy Hunge13f8a62016-03-30 14:20:42 -07001619 int32_t msec = 0;
1620 if (!mRecycledTrack->stopped()) { // check if active
1621 (void)mRecycledTrack->pendingDuration(&msec);
1622 }
1623 mRecycledTrack->stop(); // ensure full data drain
1624 ALOGD("deleting recycled track, waiting for data drain (%d msec)", msec);
1625 if (msec > 0) {
1626 static const int32_t WAIT_LIMIT_MS = 3000;
1627 if (msec > WAIT_LIMIT_MS) {
1628 msec = WAIT_LIMIT_MS;
1629 }
1630 usleep(msec * 1000LL);
1631 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001632 }
1633 // An offloaded track isn't flushed because the STREAM_END is reported
1634 // slightly prematurely to allow time for the gapless track switch
1635 // but this means that if we decide not to recycle the track there
1636 // could be a small amount of residual data still playing. We leave
1637 // AudioFlinger to drain the track.
1638
1639 mRecycledTrack.clear();
Andy Hungd1c74342015-07-07 16:54:23 -07001640 close_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001641 delete mCallbackData;
1642 mCallbackData = NULL;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001643 }
1644}
1645
Andy Hungd1c74342015-07-07 16:54:23 -07001646void MediaPlayerService::AudioOutput::close_l()
1647{
1648 mTrack.clear();
1649}
1650
Andreas Huber20111aa2009-07-14 16:56:47 -07001651status_t MediaPlayerService::AudioOutput::open(
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001652 uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
1653 audio_format_t format, int bufferCount,
Eric Laurent1948eb32012-04-13 16:50:19 -07001654 AudioCallback cb, void *cookie,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001655 audio_output_flags_t flags,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001656 const audio_offload_info_t *offloadInfo,
Andy Hung179652e2015-05-31 22:49:46 -07001657 bool doNotReconnect,
1658 uint32_t suggestedFrameCount)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001659{
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001660 ALOGV("open(%u, %d, 0x%x, 0x%x, %d, %d 0x%x)", sampleRate, channelCount, channelMask,
1661 format, bufferCount, mSessionId, flags);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001662
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001663 // offloading is only supported in callback mode for now.
1664 // offloadInfo must be present if offload flag is set
1665 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) &&
1666 ((cb == NULL) || (offloadInfo == NULL))) {
1667 return BAD_VALUE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001668 }
1669
Andy Hung179652e2015-05-31 22:49:46 -07001670 // compute frame count for the AudioTrack internal buffer
1671 size_t frameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001672 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1673 frameCount = 0; // AudioTrack will get frame count from AudioFlinger
1674 } else {
Andy Hung179652e2015-05-31 22:49:46 -07001675 // try to estimate the buffer processing fetch size from AudioFlinger.
1676 // framesPerBuffer is approximate and generally correct, except when it's not :-).
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001677 uint32_t afSampleRate;
1678 size_t afFrameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001679 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1680 return NO_INIT;
1681 }
1682 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1683 return NO_INIT;
1684 }
Andy Hung179652e2015-05-31 22:49:46 -07001685 const size_t framesPerBuffer =
1686 (unsigned long long)sampleRate * afFrameCount / afSampleRate;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001687
Andy Hung179652e2015-05-31 22:49:46 -07001688 if (bufferCount == 0) {
1689 // use suggestedFrameCount
1690 bufferCount = (suggestedFrameCount + framesPerBuffer - 1) / framesPerBuffer;
1691 }
1692 // Check argument bufferCount against the mininum buffer count
1693 if (bufferCount != 0 && bufferCount < mMinBufferCount) {
1694 ALOGV("bufferCount (%d) increased to %d", bufferCount, mMinBufferCount);
1695 bufferCount = mMinBufferCount;
1696 }
1697 // if frameCount is 0, then AudioTrack will get frame count from AudioFlinger
1698 // which will be the minimum size permitted.
1699 frameCount = bufferCount * framesPerBuffer;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001700 }
Andreas Huber20111aa2009-07-14 16:56:47 -07001701
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001702 if (channelMask == CHANNEL_MASK_USE_CHANNEL_ORDER) {
Glenn Kastenab334fd2012-03-14 12:56:06 -07001703 channelMask = audio_channel_out_mask_from_count(channelCount);
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001704 if (0 == channelMask) {
1705 ALOGE("open() error, can\'t derive mask for %d audio channels", channelCount);
1706 return NO_INIT;
1707 }
1708 }
Eric Laurent1948eb32012-04-13 16:50:19 -07001709
Andy Hungd1c74342015-07-07 16:54:23 -07001710 Mutex::Autolock lock(mLock);
Andy Hung179652e2015-05-31 22:49:46 -07001711 mCallback = cb;
1712 mCallbackCookie = cookie;
1713
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001714 // Check whether we can recycle the track
1715 bool reuse = false;
1716 bool bothOffloaded = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001717
Glenn Kasten2799d742013-05-30 14:33:29 -07001718 if (mRecycledTrack != 0) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001719 // check whether we are switching between two offloaded tracks
1720 bothOffloaded = (flags & mRecycledTrack->getFlags()
1721 & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0;
Marco Nelissen67295b52012-06-11 14:52:53 -07001722
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001723 // check if the existing track can be reused as-is, or if a new track needs to be created.
1724 reuse = true;
1725
Marco Nelissen67295b52012-06-11 14:52:53 -07001726 if ((mCallbackData == NULL && mCallback != NULL) ||
1727 (mCallbackData != NULL && mCallback == NULL)) {
1728 // recycled track uses callbacks but the caller wants to use writes, or vice versa
1729 ALOGV("can't chain callback and write");
1730 reuse = false;
1731 } else if ((mRecycledTrack->getSampleRate() != sampleRate) ||
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001732 (mRecycledTrack->channelCount() != (uint32_t)channelCount) ) {
1733 ALOGV("samplerate, channelcount differ: %u/%u Hz, %u/%d ch",
Marco Nelissen67295b52012-06-11 14:52:53 -07001734 mRecycledTrack->getSampleRate(), sampleRate,
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001735 mRecycledTrack->channelCount(), channelCount);
Marco Nelissen67295b52012-06-11 14:52:53 -07001736 reuse = false;
1737 } else if (flags != mFlags) {
1738 ALOGV("output flags differ %08x/%08x", flags, mFlags);
1739 reuse = false;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001740 } else if (mRecycledTrack->format() != format) {
1741 reuse = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001742 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001743 } else {
1744 ALOGV("no track available to recycle");
1745 }
1746
1747 ALOGV_IF(bothOffloaded, "both tracks offloaded");
1748
1749 // If we can't recycle and both tracks are offloaded
1750 // we must close the previous output before opening a new one
1751 if (bothOffloaded && !reuse) {
1752 ALOGV("both offloaded and not recycling");
Andy Hungd1c74342015-07-07 16:54:23 -07001753 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001754 }
1755
1756 sp<AudioTrack> t;
1757 CallbackData *newcbd = NULL;
1758
1759 // We don't attempt to create a new track if we are recycling an
1760 // offloaded track. But, if we are recycling a non-offloaded or we
1761 // are switching where one is offloaded and one isn't then we create
1762 // the new track in advance so that we can read additional stream info
1763
1764 if (!(reuse && bothOffloaded)) {
1765 ALOGV("creating new AudioTrack");
1766
1767 if (mCallback != NULL) {
1768 newcbd = new CallbackData(this);
1769 t = new AudioTrack(
1770 mStreamType,
1771 sampleRate,
1772 format,
1773 channelMask,
1774 frameCount,
1775 flags,
1776 CallbackWrapper,
1777 newcbd,
1778 0, // notification frames
1779 mSessionId,
1780 AudioTrack::TRANSFER_CALLBACK,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001781 offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -08001782 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001783 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001784 mAttributes,
1785 doNotReconnect);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001786 } else {
Andy Hungff874dc2016-04-11 16:49:09 -07001787 // TODO: Due to buffer memory concerns, we use a max target playback speed
1788 // based on mPlaybackRate at the time of open (instead of kMaxRequiredSpeed),
1789 // also clamping the target speed to 1.0 <= targetSpeed <= kMaxRequiredSpeed.
1790 const float targetSpeed =
1791 std::min(std::max(mPlaybackRate.mSpeed, 1.0f), kMaxRequiredSpeed);
1792 ALOGW_IF(targetSpeed != mPlaybackRate.mSpeed,
1793 "track target speed:%f clamped from playback speed:%f",
1794 targetSpeed, mPlaybackRate.mSpeed);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001795 t = new AudioTrack(
1796 mStreamType,
1797 sampleRate,
1798 format,
1799 channelMask,
1800 frameCount,
1801 flags,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001802 NULL, // callback
1803 NULL, // user data
1804 0, // notification frames
1805 mSessionId,
1806 AudioTrack::TRANSFER_DEFAULT,
1807 NULL, // offload info
Marco Nelissend457c972014-02-11 08:47:07 -08001808 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001809 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001810 mAttributes,
Andy Hungff874dc2016-04-11 16:49:09 -07001811 doNotReconnect,
1812 targetSpeed);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001813 }
1814
1815 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1816 ALOGE("Unable to create audio track");
1817 delete newcbd;
Glenn Kasten3e98ecd2015-05-18 13:13:24 -07001818 // t goes out of scope, so reference count drops to zero
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001819 return NO_INIT;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001820 } else {
1821 // successful AudioTrack initialization implies a legacy stream type was generated
1822 // from the audio attributes
1823 mStreamType = t->streamType();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001824 }
1825 }
1826
1827 if (reuse) {
1828 CHECK(mRecycledTrack != NULL);
1829
1830 if (!bothOffloaded) {
1831 if (mRecycledTrack->frameCount() != t->frameCount()) {
Andy Hung833b4752016-04-04 17:15:48 -07001832 ALOGV("framecount differs: %zu/%zu frames",
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001833 mRecycledTrack->frameCount(), t->frameCount());
1834 reuse = false;
1835 }
1836 }
1837
Marco Nelissen67295b52012-06-11 14:52:53 -07001838 if (reuse) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001839 ALOGV("chaining to next output and recycling track");
Andy Hungd1c74342015-07-07 16:54:23 -07001840 close_l();
Marco Nelissen67295b52012-06-11 14:52:53 -07001841 mTrack = mRecycledTrack;
Glenn Kasten2799d742013-05-30 14:33:29 -07001842 mRecycledTrack.clear();
Marco Nelissen67295b52012-06-11 14:52:53 -07001843 if (mCallbackData != NULL) {
1844 mCallbackData->setOutput(this);
1845 }
Marco Nelissen67295b52012-06-11 14:52:53 -07001846 delete newcbd;
1847 return OK;
1848 }
Marco Nelissen67295b52012-06-11 14:52:53 -07001849 }
1850
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001851 // we're not going to reuse the track, unblock and flush it
1852 // this was done earlier if both tracks are offloaded
1853 if (!bothOffloaded) {
Andy Hungd1c74342015-07-07 16:54:23 -07001854 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001855 }
1856
1857 CHECK((t != NULL) && ((mCallback == NULL) || (newcbd != NULL)));
1858
Marco Nelissen67295b52012-06-11 14:52:53 -07001859 mCallbackData = newcbd;
Steve Block3856b092011-10-20 11:56:00 +01001860 ALOGV("setVolume");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001861 t->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07001862
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001863 mSampleRateHz = sampleRate;
Preetam Singh Ranawat2e17eef2015-08-12 12:11:46 -07001864 mFlags = flags;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001865 mMsecsPerFrame = 1E3f / (mPlaybackRate.mSpeed * sampleRate);
Andy Hungd1c74342015-07-07 16:54:23 -07001866 mFrameSize = t->frameSize();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001867 mTrack = t;
Eric Laurent2beeb502010-07-16 07:43:46 -07001868
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001869 status_t res = NO_ERROR;
Wei Jia0162d002015-06-09 11:59:33 -07001870 // Note some output devices may give us a direct track even though we don't specify it.
1871 // Example: Line application b/17459982.
Preetam Singh Ranawat2e17eef2015-08-12 12:11:46 -07001872 if ((t->getFlags() & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) {
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001873 res = t->setPlaybackRate(mPlaybackRate);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001874 if (res == NO_ERROR) {
1875 t->setAuxEffectSendLevel(mSendLevel);
1876 res = t->attachAuxEffect(mAuxEffectId);
1877 }
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001878 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001879 ALOGV("open() DONE status %d", res);
1880 return res;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001881}
1882
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001883status_t MediaPlayerService::AudioOutput::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001884{
Steve Block3856b092011-10-20 11:56:00 +01001885 ALOGV("start");
Andy Hungd1c74342015-07-07 16:54:23 -07001886 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001887 if (mCallbackData != NULL) {
1888 mCallbackData->endTrackSwitch();
1889 }
Glenn Kasten2799d742013-05-30 14:33:29 -07001890 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001891 mTrack->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07001892 mTrack->setAuxEffectSendLevel(mSendLevel);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001893 return mTrack->start();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001894 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001895 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001896}
1897
Marco Nelissen6b74d672012-02-28 16:07:44 -08001898void MediaPlayerService::AudioOutput::setNextOutput(const sp<AudioOutput>& nextOutput) {
Andy Hungd1c74342015-07-07 16:54:23 -07001899 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001900 mNextOutput = nextOutput;
1901}
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08001902
Marco Nelissen6b74d672012-02-28 16:07:44 -08001903void MediaPlayerService::AudioOutput::switchToNextOutput() {
1904 ALOGV("switchToNextOutput");
Andy Hungd1c74342015-07-07 16:54:23 -07001905
1906 // Try to acquire the callback lock before moving track (without incurring deadlock).
1907 const unsigned kMaxSwitchTries = 100;
1908 Mutex::Autolock lock(mLock);
1909 for (unsigned tries = 0;;) {
1910 if (mTrack == 0) {
1911 return;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001912 }
Andy Hungd1c74342015-07-07 16:54:23 -07001913 if (mNextOutput != NULL && mNextOutput != this) {
1914 if (mCallbackData != NULL) {
1915 // two alternative approaches
1916#if 1
1917 CallbackData *callbackData = mCallbackData;
1918 mLock.unlock();
1919 // proper acquisition sequence
1920 callbackData->lock();
1921 mLock.lock();
1922 // Caution: it is unlikely that someone deleted our callback or changed our target
1923 if (callbackData != mCallbackData || mNextOutput == NULL || mNextOutput == this) {
1924 // fatal if we are starved out.
1925 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
1926 "switchToNextOutput() cannot obtain correct lock sequence");
1927 callbackData->unlock();
1928 continue;
1929 }
1930 callbackData->mSwitching = true; // begin track switch
1931#else
1932 // tryBeginTrackSwitch() returns false if the callback has the lock.
1933 if (!mCallbackData->tryBeginTrackSwitch()) {
1934 // fatal if we are starved out.
1935 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
1936 "switchToNextOutput() cannot obtain callback lock");
1937 mLock.unlock();
1938 usleep(5 * 1000 /* usec */); // allow callback to use AudioOutput
1939 mLock.lock();
1940 continue;
1941 }
1942#endif
1943 }
1944
1945 Mutex::Autolock nextLock(mNextOutput->mLock);
1946
1947 // If the next output track is not NULL, then it has been
1948 // opened already for playback.
1949 // This is possible even without the next player being started,
1950 // for example, the next player could be prepared and seeked.
1951 //
1952 // Presuming it isn't advisable to force the track over.
1953 if (mNextOutput->mTrack == NULL) {
1954 ALOGD("Recycling track for gapless playback");
1955 delete mNextOutput->mCallbackData;
1956 mNextOutput->mCallbackData = mCallbackData;
1957 mNextOutput->mRecycledTrack = mTrack;
1958 mNextOutput->mSampleRateHz = mSampleRateHz;
1959 mNextOutput->mMsecsPerFrame = mMsecsPerFrame;
Andy Hungd1c74342015-07-07 16:54:23 -07001960 mNextOutput->mFlags = mFlags;
1961 mNextOutput->mFrameSize = mFrameSize;
1962 close_l();
1963 mCallbackData = NULL; // destruction handled by mNextOutput
1964 } else {
1965 ALOGW("Ignoring gapless playback because next player has already started");
1966 // remove track in case resource needed for future players.
1967 if (mCallbackData != NULL) {
1968 mCallbackData->endTrackSwitch(); // release lock for callbacks before close.
1969 }
1970 close_l();
1971 }
1972 }
1973 break;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001974 }
1975}
1976
Wei Jia7d3f4df2015-03-03 15:28:00 -08001977ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001978{
Andy Hungd1c74342015-07-07 16:54:23 -07001979 Mutex::Autolock lock(mLock);
Glenn Kastenadad3d72014-02-21 14:51:43 -08001980 LOG_ALWAYS_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
Andreas Huber20111aa2009-07-14 16:56:47 -07001981
Steve Block3856b092011-10-20 11:56:00 +01001982 //ALOGV("write(%p, %u)", buffer, size);
Glenn Kasten2799d742013-05-30 14:33:29 -07001983 if (mTrack != 0) {
Andy Hung2f6e73d2016-04-08 12:12:58 -07001984 return mTrack->write(buffer, size, blocking);
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001985 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001986 return NO_INIT;
1987}
1988
1989void MediaPlayerService::AudioOutput::stop()
1990{
Steve Block3856b092011-10-20 11:56:00 +01001991 ALOGV("stop");
Andy Hungd1c74342015-07-07 16:54:23 -07001992 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07001993 if (mTrack != 0) mTrack->stop();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001994}
1995
1996void MediaPlayerService::AudioOutput::flush()
1997{
Steve Block3856b092011-10-20 11:56:00 +01001998 ALOGV("flush");
Andy Hungd1c74342015-07-07 16:54:23 -07001999 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002000 if (mTrack != 0) mTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002001}
2002
2003void MediaPlayerService::AudioOutput::pause()
2004{
Steve Block3856b092011-10-20 11:56:00 +01002005 ALOGV("pause");
Andy Hungd1c74342015-07-07 16:54:23 -07002006 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002007 if (mTrack != 0) mTrack->pause();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002008}
2009
2010void MediaPlayerService::AudioOutput::close()
2011{
Steve Block3856b092011-10-20 11:56:00 +01002012 ALOGV("close");
Erik Wolsheimer7845a1f2015-10-30 12:07:52 -07002013 sp<AudioTrack> track;
2014 {
2015 Mutex::Autolock lock(mLock);
2016 track = mTrack;
2017 close_l(); // clears mTrack
2018 }
2019 // destruction of the track occurs outside of mutex.
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002020}
2021
2022void MediaPlayerService::AudioOutput::setVolume(float left, float right)
2023{
Steve Block3856b092011-10-20 11:56:00 +01002024 ALOGV("setVolume(%f, %f)", left, right);
Andy Hungd1c74342015-07-07 16:54:23 -07002025 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002026 mLeftVolume = left;
2027 mRightVolume = right;
Glenn Kasten2799d742013-05-30 14:33:29 -07002028 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002029 mTrack->setVolume(left, right);
2030 }
2031}
2032
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002033status_t MediaPlayerService::AudioOutput::setPlaybackRate(const AudioPlaybackRate &rate)
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002034{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002035 ALOGV("setPlaybackRate(%f %f %d %d)",
2036 rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Andy Hungd1c74342015-07-07 16:54:23 -07002037 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002038 if (mTrack == 0) {
2039 // remember rate so that we can set it when the track is opened
2040 mPlaybackRate = rate;
2041 return OK;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002042 }
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002043 status_t res = mTrack->setPlaybackRate(rate);
2044 if (res != NO_ERROR) {
2045 return res;
2046 }
2047 // rate.mSpeed is always greater than 0 if setPlaybackRate succeeded
2048 CHECK_GT(rate.mSpeed, 0.f);
2049 mPlaybackRate = rate;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002050 if (mSampleRateHz != 0) {
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002051 mMsecsPerFrame = 1E3f / (rate.mSpeed * mSampleRateHz);
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002052 }
2053 return res;
2054}
2055
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002056status_t MediaPlayerService::AudioOutput::getPlaybackRate(AudioPlaybackRate *rate)
2057{
2058 ALOGV("setPlaybackRate");
Andy Hungd1c74342015-07-07 16:54:23 -07002059 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002060 if (mTrack == 0) {
2061 return NO_INIT;
2062 }
2063 *rate = mTrack->getPlaybackRate();
2064 return NO_ERROR;
2065}
2066
Eric Laurent2beeb502010-07-16 07:43:46 -07002067status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
2068{
Steve Block3856b092011-10-20 11:56:00 +01002069 ALOGV("setAuxEffectSendLevel(%f)", level);
Andy Hungd1c74342015-07-07 16:54:23 -07002070 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002071 mSendLevel = level;
Glenn Kasten2799d742013-05-30 14:33:29 -07002072 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002073 return mTrack->setAuxEffectSendLevel(level);
2074 }
2075 return NO_ERROR;
2076}
2077
2078status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
2079{
Steve Block3856b092011-10-20 11:56:00 +01002080 ALOGV("attachAuxEffect(%d)", effectId);
Andy Hungd1c74342015-07-07 16:54:23 -07002081 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002082 mAuxEffectId = effectId;
Glenn Kasten2799d742013-05-30 14:33:29 -07002083 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002084 return mTrack->attachAuxEffect(effectId);
2085 }
2086 return NO_ERROR;
2087}
2088
Andreas Huber20111aa2009-07-14 16:56:47 -07002089// static
2090void MediaPlayerService::AudioOutput::CallbackWrapper(
Glenn Kastend217a8c2011-06-01 15:20:35 -07002091 int event, void *cookie, void *info) {
Steve Block3856b092011-10-20 11:56:00 +01002092 //ALOGV("callbackwrapper");
Marco Nelissen6b74d672012-02-28 16:07:44 -08002093 CallbackData *data = (CallbackData*)cookie;
Andy Hungd1c74342015-07-07 16:54:23 -07002094 // lock to ensure we aren't caught in the middle of a track switch.
Marco Nelissen6b74d672012-02-28 16:07:44 -08002095 data->lock();
2096 AudioOutput *me = data->getOutput();
Andreas Huber20111aa2009-07-14 16:56:47 -07002097 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002098 if (me == NULL) {
2099 // no output set, likely because the track was scheduled to be reused
2100 // by another player, but the format turned out to be incompatible.
2101 data->unlock();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002102 if (buffer != NULL) {
2103 buffer->size = 0;
2104 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08002105 return;
2106 }
Andreas Huber20111aa2009-07-14 16:56:47 -07002107
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002108 switch(event) {
2109 case AudioTrack::EVENT_MORE_DATA: {
2110 size_t actualSize = (*me->mCallback)(
2111 me, buffer->raw, buffer->size, me->mCallbackCookie,
2112 CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002113
Andy Hung719b46b2015-05-31 22:18:25 -07002114 // Log when no data is returned from the callback.
2115 // (1) We may have no data (especially with network streaming sources).
2116 // (2) We may have reached the EOS and the audio track is not stopped yet.
2117 // Note that AwesomePlayer/AudioPlayer will only return zero size when it reaches the EOS.
2118 // NuPlayerRenderer will return zero when it doesn't have data (it doesn't block to fill).
2119 //
2120 // This is a benign busy-wait, with the next data request generated 10 ms or more later;
2121 // nevertheless for power reasons, we don't want to see too many of these.
Andreas Huber2e8ffaf2010-02-18 16:45:13 -08002122
Andy Hung719b46b2015-05-31 22:18:25 -07002123 ALOGV_IF(actualSize == 0 && buffer->size > 0, "callbackwrapper: empty buffer returned");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002124
2125 buffer->size = actualSize;
2126 } break;
2127
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002128 case AudioTrack::EVENT_STREAM_END:
Andy Hung719b46b2015-05-31 22:18:25 -07002129 // currently only occurs for offloaded callbacks
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002130 ALOGV("callbackwrapper: deliver EVENT_STREAM_END");
2131 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2132 me->mCallbackCookie, CB_EVENT_STREAM_END);
2133 break;
2134
2135 case AudioTrack::EVENT_NEW_IAUDIOTRACK :
2136 ALOGV("callbackwrapper: deliver EVENT_TEAR_DOWN");
2137 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2138 me->mCallbackCookie, CB_EVENT_TEAR_DOWN);
2139 break;
2140
Glenn Kasten421743b2015-06-01 08:18:08 -07002141 case AudioTrack::EVENT_UNDERRUN:
Andy Hung719b46b2015-05-31 22:18:25 -07002142 // This occurs when there is no data available, typically
Glenn Kasten421743b2015-06-01 08:18:08 -07002143 // when there is a failure to supply data to the AudioTrack. It can also
2144 // occur in non-offloaded mode when the audio device comes out of standby.
2145 //
Andy Hung719b46b2015-05-31 22:18:25 -07002146 // If an AudioTrack underruns it outputs silence. Since this happens suddenly
2147 // it may sound like an audible pop or glitch.
2148 //
2149 // The underrun event is sent once per track underrun; the condition is reset
2150 // when more data is sent to the AudioTrack.
Eric Laurente93cc032016-05-05 10:15:10 -07002151 ALOGD("callbackwrapper: EVENT_UNDERRUN (discarded)");
Glenn Kasten421743b2015-06-01 08:18:08 -07002152 break;
2153
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002154 default:
2155 ALOGE("received unknown event type: %d inside CallbackWrapper !", event);
Andreas Huber51c1e0e2011-04-04 11:43:40 -07002156 }
2157
Marco Nelissen6b74d672012-02-28 16:07:44 -08002158 data->unlock();
Andreas Huber20111aa2009-07-14 16:56:47 -07002159}
2160
Glenn Kastend848eb42016-03-08 13:42:11 -08002161audio_session_t MediaPlayerService::AudioOutput::getSessionId() const
Eric Laurent8c563ed2010-10-07 18:23:03 -07002162{
Andy Hungd1c74342015-07-07 16:54:23 -07002163 Mutex::Autolock lock(mLock);
Eric Laurent8c563ed2010-10-07 18:23:03 -07002164 return mSessionId;
2165}
2166
Eric Laurent6f59db12013-07-26 17:16:50 -07002167uint32_t MediaPlayerService::AudioOutput::getSampleRate() const
2168{
Andy Hungd1c74342015-07-07 16:54:23 -07002169 Mutex::Autolock lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -07002170 if (mTrack == 0) return 0;
2171 return mTrack->getSampleRate();
2172}
2173
Andy Hungf2c87b32016-04-07 19:49:29 -07002174int64_t MediaPlayerService::AudioOutput::getBufferDurationInUs() const
2175{
2176 Mutex::Autolock lock(mLock);
2177 if (mTrack == 0) {
2178 return 0;
2179 }
2180 int64_t duration;
2181 if (mTrack->getBufferDurationInUs(&duration) != OK) {
2182 return 0;
2183 }
2184 return duration;
2185}
2186
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002187////////////////////////////////////////////////////////////////////////////////
2188
2189struct CallbackThread : public Thread {
2190 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
2191 MediaPlayerBase::AudioSink::AudioCallback cb,
2192 void *cookie);
2193
2194protected:
2195 virtual ~CallbackThread();
2196
2197 virtual bool threadLoop();
2198
2199private:
2200 wp<MediaPlayerBase::AudioSink> mSink;
2201 MediaPlayerBase::AudioSink::AudioCallback mCallback;
2202 void *mCookie;
2203 void *mBuffer;
2204 size_t mBufferSize;
2205
2206 CallbackThread(const CallbackThread &);
2207 CallbackThread &operator=(const CallbackThread &);
2208};
2209
2210CallbackThread::CallbackThread(
2211 const wp<MediaPlayerBase::AudioSink> &sink,
2212 MediaPlayerBase::AudioSink::AudioCallback cb,
2213 void *cookie)
2214 : mSink(sink),
2215 mCallback(cb),
2216 mCookie(cookie),
2217 mBuffer(NULL),
2218 mBufferSize(0) {
2219}
2220
2221CallbackThread::~CallbackThread() {
2222 if (mBuffer) {
2223 free(mBuffer);
2224 mBuffer = NULL;
2225 }
2226}
2227
2228bool CallbackThread::threadLoop() {
2229 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
2230 if (sink == NULL) {
2231 return false;
2232 }
2233
2234 if (mBuffer == NULL) {
2235 mBufferSize = sink->bufferSize();
2236 mBuffer = malloc(mBufferSize);
2237 }
2238
2239 size_t actualSize =
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002240 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie,
2241 MediaPlayerBase::AudioSink::CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002242
2243 if (actualSize > 0) {
2244 sink->write(mBuffer, actualSize);
Andy Hunga31335a2014-08-20 17:37:59 -07002245 // Could return false on sink->write() error or short count.
2246 // Not necessarily appropriate but would work for AudioCache behavior.
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002247 }
2248
2249 return true;
2250}
2251
2252////////////////////////////////////////////////////////////////////////////////
2253
Gloria Wang7cf180c2011-02-19 18:37:57 -08002254void MediaPlayerService::addBatteryData(uint32_t params)
2255{
2256 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002257
2258 int32_t time = systemTime() / 1000000L;
2259
2260 // change audio output devices. This notification comes from AudioFlinger
2261 if ((params & kBatteryDataSpeakerOn)
2262 || (params & kBatteryDataOtherAudioDeviceOn)) {
2263
2264 int deviceOn[NUM_AUDIO_DEVICES];
2265 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2266 deviceOn[i] = 0;
2267 }
2268
2269 if ((params & kBatteryDataSpeakerOn)
2270 && (params & kBatteryDataOtherAudioDeviceOn)) {
2271 deviceOn[SPEAKER_AND_OTHER] = 1;
2272 } else if (params & kBatteryDataSpeakerOn) {
2273 deviceOn[SPEAKER] = 1;
2274 } else {
2275 deviceOn[OTHER_AUDIO_DEVICE] = 1;
2276 }
2277
2278 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2279 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
2280
2281 if (mBatteryAudio.refCount > 0) { // if playing audio
2282 if (!deviceOn[i]) {
2283 mBatteryAudio.lastTime[i] += time;
2284 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2285 mBatteryAudio.lastTime[i] = 0;
2286 } else {
2287 mBatteryAudio.lastTime[i] = 0 - time;
2288 }
2289 }
2290
2291 mBatteryAudio.deviceOn[i] = deviceOn[i];
2292 }
2293 }
2294 return;
2295 }
2296
Marco Nelissenb7848f12014-12-04 08:57:56 -08002297 // an audio stream is started
Gloria Wang9ee159b2011-02-24 14:51:45 -08002298 if (params & kBatteryDataAudioFlingerStart) {
2299 // record the start time only if currently no other audio
2300 // is being played
2301 if (mBatteryAudio.refCount == 0) {
2302 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2303 if (mBatteryAudio.deviceOn[i]) {
2304 mBatteryAudio.lastTime[i] -= time;
2305 }
2306 }
2307 }
2308
2309 mBatteryAudio.refCount ++;
2310 return;
2311
2312 } else if (params & kBatteryDataAudioFlingerStop) {
2313 if (mBatteryAudio.refCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002314 ALOGW("Battery track warning: refCount is <= 0");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002315 return;
2316 }
2317
2318 // record the stop time only if currently this is the only
2319 // audio being played
2320 if (mBatteryAudio.refCount == 1) {
2321 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2322 if (mBatteryAudio.deviceOn[i]) {
2323 mBatteryAudio.lastTime[i] += time;
2324 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2325 mBatteryAudio.lastTime[i] = 0;
2326 }
2327 }
2328 }
2329
2330 mBatteryAudio.refCount --;
2331 return;
2332 }
2333
Gloria Wang7cf180c2011-02-19 18:37:57 -08002334 int uid = IPCThreadState::self()->getCallingUid();
2335 if (uid == AID_MEDIA) {
2336 return;
2337 }
2338 int index = mBatteryData.indexOfKey(uid);
Gloria Wang7cf180c2011-02-19 18:37:57 -08002339
2340 if (index < 0) { // create a new entry for this UID
2341 BatteryUsageInfo info;
2342 info.audioTotalTime = 0;
2343 info.videoTotalTime = 0;
2344 info.audioLastTime = 0;
2345 info.videoLastTime = 0;
2346 info.refCount = 0;
2347
Gloria Wang9ee159b2011-02-24 14:51:45 -08002348 if (mBatteryData.add(uid, info) == NO_MEMORY) {
Steve Block29357bc2012-01-06 19:20:56 +00002349 ALOGE("Battery track error: no memory for new app");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002350 return;
2351 }
Gloria Wang7cf180c2011-02-19 18:37:57 -08002352 }
2353
2354 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
2355
2356 if (params & kBatteryDataCodecStarted) {
2357 if (params & kBatteryDataTrackAudio) {
2358 info.audioLastTime -= time;
2359 info.refCount ++;
2360 }
2361 if (params & kBatteryDataTrackVideo) {
2362 info.videoLastTime -= time;
2363 info.refCount ++;
2364 }
2365 } else {
2366 if (info.refCount == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002367 ALOGW("Battery track warning: refCount is already 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002368 return;
2369 } else if (info.refCount < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00002370 ALOGE("Battery track error: refCount < 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002371 mBatteryData.removeItem(uid);
2372 return;
2373 }
2374
2375 if (params & kBatteryDataTrackAudio) {
2376 info.audioLastTime += time;
2377 info.refCount --;
2378 }
2379 if (params & kBatteryDataTrackVideo) {
2380 info.videoLastTime += time;
2381 info.refCount --;
2382 }
2383
2384 // no stream is being played by this UID
2385 if (info.refCount == 0) {
2386 info.audioTotalTime += info.audioLastTime;
2387 info.audioLastTime = 0;
2388 info.videoTotalTime += info.videoLastTime;
2389 info.videoLastTime = 0;
2390 }
2391 }
2392}
2393
2394status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
2395 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002396
2397 // audio output devices usage
2398 int32_t time = systemTime() / 1000000L; //in ms
2399 int32_t totalTime;
2400
2401 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2402 totalTime = mBatteryAudio.totalTime[i];
2403
2404 if (mBatteryAudio.deviceOn[i]
2405 && (mBatteryAudio.lastTime[i] != 0)) {
2406 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
2407 totalTime += tmpTime;
2408 }
2409
2410 reply->writeInt32(totalTime);
2411 // reset the total time
2412 mBatteryAudio.totalTime[i] = 0;
2413 }
2414
2415 // codec usage
Gloria Wang7cf180c2011-02-19 18:37:57 -08002416 BatteryUsageInfo info;
2417 int size = mBatteryData.size();
2418
2419 reply->writeInt32(size);
2420 int i = 0;
2421
2422 while (i < size) {
2423 info = mBatteryData.valueAt(i);
2424
2425 reply->writeInt32(mBatteryData.keyAt(i)); //UID
2426 reply->writeInt32(info.audioTotalTime);
2427 reply->writeInt32(info.videoTotalTime);
2428
2429 info.audioTotalTime = 0;
2430 info.videoTotalTime = 0;
2431
2432 // remove the UID entry where no stream is being played
2433 if (info.refCount <= 0) {
2434 mBatteryData.removeItemsAt(i);
2435 size --;
2436 i --;
2437 }
2438 i++;
2439 }
2440 return NO_ERROR;
2441}
nikoa64c8c72009-07-20 15:07:26 -07002442} // namespace android