blob: 3cfed5e8764790caa6b1e8764edc944d5f120822 [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;
Sergio Giro1d3f4272016-06-28 18:24:52 +0100240 utf16_to_utf8(tags.string(), tagSize, attributes->tags,
241 sizeof(attributes->tags) / sizeof(attributes->tags[0]));
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700242 }
243 } else {
244 ALOGE("unmarshallAudioAttributes() received unflattened tags, ignoring tag values");
245 strcpy(attributes->tags, "");
246 }
247}
248} // anonymous namespace
249
250
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800251namespace android {
252
Marco Nelissenf09611f2015-02-13 14:12:42 -0800253extern ALooperRoster gLooperRoster;
254
255
Dave Burked681bbb2011-08-30 14:39:17 +0100256static bool checkPermission(const char* permissionString) {
Dave Burked681bbb2011-08-30 14:39:17 +0100257 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
258 bool ok = checkCallingPermission(String16(permissionString));
Steve Block29357bc2012-01-06 19:20:56 +0000259 if (!ok) ALOGE("Request requires %s", permissionString);
Dave Burked681bbb2011-08-30 14:39:17 +0100260 return ok;
261}
262
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800263// TODO: Find real cause of Audio/Video delay in PV framework and remove this workaround
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800264/* static */ int MediaPlayerService::AudioOutput::mMinBufferCount = 4;
265/* static */ bool MediaPlayerService::AudioOutput::mIsOnEmulator = false;
266
267void MediaPlayerService::instantiate() {
268 defaultServiceManager()->addService(
269 String16("media.player"), new MediaPlayerService());
270}
271
272MediaPlayerService::MediaPlayerService()
273{
Steve Block3856b092011-10-20 11:56:00 +0100274 ALOGV("MediaPlayerService created");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800275 mNextConnId = 1;
Gloria Wang9ee159b2011-02-24 14:51:45 -0800276
277 mBatteryAudio.refCount = 0;
278 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
279 mBatteryAudio.deviceOn[i] = 0;
280 mBatteryAudio.lastTime[i] = 0;
281 mBatteryAudio.totalTime[i] = 0;
282 }
283 // speaker is on by default
284 mBatteryAudio.deviceOn[SPEAKER] = 1;
John Grossman44a7e422012-06-21 17:29:24 -0700285
Chong Zhang0b30fd42014-07-23 14:46:05 -0700286 // reset battery stats
287 // if the mediaserver has crashed, battery stats could be left
288 // in bad state, reset the state upon service start.
Wei Jia3f273d12015-11-24 09:06:49 -0800289 BatteryNotifier::getInstance().noteResetVideo();
Chong Zhang0b30fd42014-07-23 14:46:05 -0700290
John Grossman44a7e422012-06-21 17:29:24 -0700291 MediaPlayerFactory::registerBuiltinFactories();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800292}
293
294MediaPlayerService::~MediaPlayerService()
295{
Steve Block3856b092011-10-20 11:56:00 +0100296 ALOGV("MediaPlayerService destroyed");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800297}
298
Svet Ganovbe71aa22015-04-28 12:06:02 -0700299sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(const String16 &opPackageName)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800300{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800301 pid_t pid = IPCThreadState::self()->getCallingPid();
Svet Ganovbe71aa22015-04-28 12:06:02 -0700302 sp<MediaRecorderClient> recorder = new MediaRecorderClient(this, pid, opPackageName);
Gloria Wangdac6a312009-10-29 15:46:37 -0700303 wp<MediaRecorderClient> w = recorder;
304 Mutex::Autolock lock(mLock);
305 mMediaRecorderClients.add(w);
Steve Block3856b092011-10-20 11:56:00 +0100306 ALOGV("Create new media recorder client from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800307 return recorder;
308}
309
Gloria Wangdac6a312009-10-29 15:46:37 -0700310void MediaPlayerService::removeMediaRecorderClient(wp<MediaRecorderClient> client)
311{
312 Mutex::Autolock lock(mLock);
313 mMediaRecorderClients.remove(client);
Steve Block3856b092011-10-20 11:56:00 +0100314 ALOGV("Delete media recorder client");
Gloria Wangdac6a312009-10-29 15:46:37 -0700315}
316
Glenn Kastenf37971f2012-02-03 11:06:53 -0800317sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800318{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800319 pid_t pid = IPCThreadState::self()->getCallingPid();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800320 sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
Steve Block3856b092011-10-20 11:56:00 +0100321 ALOGV("Create new media retriever from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800322 return retriever;
323}
324
Glenn Kastenf37971f2012-02-03 11:06:53 -0800325sp<IMediaPlayer> MediaPlayerService::create(const sp<IMediaPlayerClient>& client,
Glenn Kastend848eb42016-03-08 13:42:11 -0800326 audio_session_t audioSessionId)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800327{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800328 pid_t pid = IPCThreadState::self()->getCallingPid();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800329 int32_t connId = android_atomic_inc(&mNextConnId);
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700330
331 sp<Client> c = new Client(
332 this, pid, connId, client, audioSessionId,
333 IPCThreadState::self()->getCallingUid());
334
Steve Block3856b092011-10-20 11:56:00 +0100335 ALOGV("Create new client(%d) from pid %d, uid %d, ", connId, pid,
Dave Burked681bbb2011-08-30 14:39:17 +0100336 IPCThreadState::self()->getCallingUid());
337
338 wp<Client> w = c;
339 {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800340 Mutex::Autolock lock(mLock);
341 mClients.add(w);
342 }
Andreas Hubere2b10282010-11-23 11:41:34 -0800343 return c;
344}
345
Lajos Molnar1381d4b2014-08-07 15:18:35 -0700346sp<IMediaCodecList> MediaPlayerService::getCodecList() const {
347 return MediaCodecList::getLocalInstance();
348}
349
Marco Nelissen260e56c2016-01-28 21:41:25 +0000350sp<IOMX> MediaPlayerService::getOMX() {
Marco Nelissen1900e772016-02-02 16:12:16 -0800351 ALOGI("MediaPlayerService::getOMX");
Marco Nelissen260e56c2016-01-28 21:41:25 +0000352 Mutex::Autolock autoLock(mLock);
353
354 if (mOMX.get() == NULL) {
355 mOMX = new OMX;
356 }
357
358 return mOMX;
359}
360
Andreas Huber279dcd82013-01-30 10:41:25 -0800361sp<IHDCP> MediaPlayerService::makeHDCP(bool createEncryptionModule) {
362 return new HDCP(createEncryptionModule);
Andreas Huber59451f82012-09-18 10:36:32 -0700363}
364
Jeff Brown2013a542012-09-04 21:38:42 -0700365sp<IRemoteDisplay> MediaPlayerService::listenForRemoteDisplay(
Svet Ganovbe71aa22015-04-28 12:06:02 -0700366 const String16 &opPackageName,
Jeff Brown2013a542012-09-04 21:38:42 -0700367 const sp<IRemoteDisplayClient>& client, const String8& iface) {
Jeff Brownaba33d52012-09-07 17:38:58 -0700368 if (!checkPermission("android.permission.CONTROL_WIFI_DISPLAY")) {
369 return NULL;
370 }
371
Svet Ganovbe71aa22015-04-28 12:06:02 -0700372 return new RemoteDisplay(opPackageName, client, iface.string());
Jeff Brown2013a542012-09-04 21:38:42 -0700373}
374
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800375status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
376{
377 const size_t SIZE = 256;
378 char buffer[SIZE];
379 String8 result;
380
381 result.append(" AudioOutput\n");
382 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n",
383 mStreamType, mLeftVolume, mRightVolume);
384 result.append(buffer);
385 snprintf(buffer, 255, " msec per frame(%f), latency (%d)\n",
Eric Laurentdb354e52012-03-05 17:27:11 -0800386 mMsecsPerFrame, (mTrack != 0) ? mTrack->latency() : -1);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800387 result.append(buffer);
Eric Laurent2beeb502010-07-16 07:43:46 -0700388 snprintf(buffer, 255, " aux effect id(%d), send level (%f)\n",
389 mAuxEffectId, mSendLevel);
390 result.append(buffer);
391
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800392 ::write(fd, result.string(), result.size());
393 if (mTrack != 0) {
394 mTrack->dump(fd, args);
395 }
396 return NO_ERROR;
397}
398
Lajos Molnar6d339f12015-04-17 16:15:53 -0700399status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800400{
401 const size_t SIZE = 256;
402 char buffer[SIZE];
403 String8 result;
404 result.append(" Client\n");
405 snprintf(buffer, 255, " pid(%d), connId(%d), status(%d), looping(%s)\n",
406 mPid, mConnId, mStatus, mLoop?"true": "false");
407 result.append(buffer);
408 write(fd, result.string(), result.size());
Andreas Hubera0b1d4b2011-06-07 15:52:25 -0700409 if (mPlayer != NULL) {
410 mPlayer->dump(fd, args);
411 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800412 if (mAudioOutput != 0) {
413 mAudioOutput->dump(fd, args);
414 }
415 write(fd, "\n", 1);
416 return NO_ERROR;
417}
418
Marco Nelissenf09611f2015-02-13 14:12:42 -0800419/**
420 * The only arguments this understands right now are -c, -von and -voff,
421 * which are parsed by ALooperRoster::dump()
422 */
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800423status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
424{
425 const size_t SIZE = 256;
426 char buffer[SIZE];
427 String8 result;
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530428 SortedVector< sp<Client> > clients; //to serialise the mutex unlock & client destruction.
429 SortedVector< sp<MediaRecorderClient> > mediaRecorderClients;
430
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800431 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
432 snprintf(buffer, SIZE, "Permission Denial: "
433 "can't dump MediaPlayerService from pid=%d, uid=%d\n",
434 IPCThreadState::self()->getCallingPid(),
435 IPCThreadState::self()->getCallingUid());
436 result.append(buffer);
437 } else {
438 Mutex::Autolock lock(mLock);
439 for (int i = 0, n = mClients.size(); i < n; ++i) {
440 sp<Client> c = mClients[i].promote();
441 if (c != 0) c->dump(fd, args);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530442 clients.add(c);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800443 }
James Dongb9141222010-07-08 11:16:11 -0700444 if (mMediaRecorderClients.size() == 0) {
445 result.append(" No media recorder client\n\n");
446 } else {
447 for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
448 sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
James Donge579e282011-10-18 22:29:20 -0700449 if (c != 0) {
450 snprintf(buffer, 255, " MediaRecorderClient pid(%d)\n", c->mPid);
451 result.append(buffer);
452 write(fd, result.string(), result.size());
453 result = "\n";
454 c->dump(fd, args);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530455 mediaRecorderClients.add(c);
James Donge579e282011-10-18 22:29:20 -0700456 }
James Dongb9141222010-07-08 11:16:11 -0700457 }
Gloria Wangdac6a312009-10-29 15:46:37 -0700458 }
459
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800460 result.append(" Files opened and/or mapped:\n");
Marco Nelissenf09611f2015-02-13 14:12:42 -0800461 snprintf(buffer, SIZE, "/proc/%d/maps", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800462 FILE *f = fopen(buffer, "r");
463 if (f) {
464 while (!feof(f)) {
465 fgets(buffer, SIZE, f);
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700466 if (strstr(buffer, " /storage/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800467 strstr(buffer, " /system/sounds/") ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700468 strstr(buffer, " /data/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800469 strstr(buffer, " /system/media/")) {
470 result.append(" ");
471 result.append(buffer);
472 }
473 }
474 fclose(f);
475 } else {
476 result.append("couldn't open ");
477 result.append(buffer);
478 result.append("\n");
479 }
480
Marco Nelissenf09611f2015-02-13 14:12:42 -0800481 snprintf(buffer, SIZE, "/proc/%d/fd", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800482 DIR *d = opendir(buffer);
483 if (d) {
484 struct dirent *ent;
485 while((ent = readdir(d)) != NULL) {
486 if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
Marco Nelissenf09611f2015-02-13 14:12:42 -0800487 snprintf(buffer, SIZE, "/proc/%d/fd/%s", getpid(), ent->d_name);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800488 struct stat s;
489 if (lstat(buffer, &s) == 0) {
490 if ((s.st_mode & S_IFMT) == S_IFLNK) {
491 char linkto[256];
492 int len = readlink(buffer, linkto, sizeof(linkto));
493 if(len > 0) {
494 if(len > 255) {
495 linkto[252] = '.';
496 linkto[253] = '.';
497 linkto[254] = '.';
498 linkto[255] = 0;
499 } else {
500 linkto[len] = 0;
501 }
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700502 if (strstr(linkto, "/storage/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800503 strstr(linkto, "/system/sounds/") == linkto ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700504 strstr(linkto, "/data/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800505 strstr(linkto, "/system/media/") == linkto) {
506 result.append(" ");
507 result.append(buffer);
508 result.append(" -> ");
509 result.append(linkto);
510 result.append("\n");
511 }
512 }
513 } else {
514 result.append(" unexpected type for ");
515 result.append(buffer);
516 result.append("\n");
517 }
518 }
519 }
520 }
521 closedir(d);
522 } else {
523 result.append("couldn't open ");
524 result.append(buffer);
525 result.append("\n");
526 }
527
Marco Nelissenf09611f2015-02-13 14:12:42 -0800528 gLooperRoster.dump(fd, args);
529
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800530 bool dumpMem = false;
Andy Hung53541292016-04-13 16:48:51 -0700531 bool unreachableMemory = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800532 for (size_t i = 0; i < args.size(); i++) {
533 if (args[i] == String16("-m")) {
534 dumpMem = true;
Andy Hung53541292016-04-13 16:48:51 -0700535 } else if (args[i] == String16("--unreachable")) {
536 unreachableMemory = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800537 }
538 }
539 if (dumpMem) {
Andy Hung07b745e2016-05-23 16:21:07 -0700540 result.append("\nDumping memory:\n");
541 std::string s = dumpMemoryAddresses(100 /* limit */);
542 result.append(s.c_str(), s.size());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800543 }
Andy Hung53541292016-04-13 16:48:51 -0700544 if (unreachableMemory) {
545 result.append("\nDumping unreachable memory:\n");
546 // TODO - should limit be an argument parameter?
547 std::string s = GetUnreachableMemoryString(true /* contents */, 10000 /* limit */);
548 result.append(s.c_str(), s.size());
549 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800550 }
551 write(fd, result.string(), result.size());
552 return NO_ERROR;
553}
554
555void MediaPlayerService::removeClient(wp<Client> client)
556{
557 Mutex::Autolock lock(mLock);
558 mClients.remove(client);
559}
560
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700561MediaPlayerService::Client::Client(
562 const sp<MediaPlayerService>& service, pid_t pid,
563 int32_t connId, const sp<IMediaPlayerClient>& client,
Glenn Kastend848eb42016-03-08 13:42:11 -0800564 audio_session_t audioSessionId, uid_t uid)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800565{
Steve Block3856b092011-10-20 11:56:00 +0100566 ALOGV("Client(%d) constructor", connId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800567 mPid = pid;
568 mConnId = connId;
569 mService = service;
570 mClient = client;
571 mLoop = false;
572 mStatus = NO_INIT;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700573 mAudioSessionId = audioSessionId;
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700574 mUID = uid;
John Grossmanc795b642012-02-22 15:38:35 -0800575 mRetransmitEndpointValid = false;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700576 mAudioAttributes = NULL;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700577
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800578#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000579 ALOGD("create Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800580 mAntagonizer = new Antagonizer(notify, this);
581#endif
582}
583
584MediaPlayerService::Client::~Client()
585{
Steve Block3856b092011-10-20 11:56:00 +0100586 ALOGV("Client(%d) destructor pid = %d", mConnId, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800587 mAudioOutput.clear();
588 wp<Client> client(this);
589 disconnect();
590 mService->removeClient(client);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700591 if (mAudioAttributes != NULL) {
592 free(mAudioAttributes);
593 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800594}
595
596void MediaPlayerService::Client::disconnect()
597{
Steve Block3856b092011-10-20 11:56:00 +0100598 ALOGV("disconnect(%d) from pid %d", mConnId, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800599 // grab local reference and clear main reference to prevent future
600 // access to object
601 sp<MediaPlayerBase> p;
602 {
603 Mutex::Autolock l(mLock);
604 p = mPlayer;
beanzdcfefde2012-11-05 09:51:43 +0800605 mClient.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800606 }
Andreas Huber20111aa2009-07-14 16:56:47 -0700607
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800608 mPlayer.clear();
609
610 // clear the notification to prevent callbacks to dead client
611 // and reset the player. We assume the player will serialize
612 // access to itself if necessary.
613 if (p != 0) {
614 p->setNotifyCallback(0, 0);
615#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000616 ALOGD("kill Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800617 mAntagonizer->kill();
618#endif
619 p->reset();
620 }
621
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700622 disconnectNativeWindow();
623
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800624 IPCThreadState::self()->flushCommands();
625}
626
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800627sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
628{
629 // determine if we have the right player type
630 sp<MediaPlayerBase> p = mPlayer;
631 if ((p != NULL) && (p->playerType() != playerType)) {
Steve Block3856b092011-10-20 11:56:00 +0100632 ALOGV("delete player");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800633 p.clear();
634 }
635 if (p == NULL) {
Ronghua Wu68845c12015-07-21 09:50:48 -0700636 p = MediaPlayerFactory::createPlayer(playerType, this, notify, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800637 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700638
Jason Simmonsdb29e522011-08-12 13:46:55 -0700639 if (p != NULL) {
640 p->setUID(mUID);
641 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700642
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800643 return p;
644}
645
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700646MediaPlayerService::Client::ServiceDeathNotifier::ServiceDeathNotifier(
647 const sp<IBinder>& service,
648 const sp<MediaPlayerBase>& listener,
649 int which) {
650 mService = service;
651 mListener = listener;
652 mWhich = which;
653}
654
655MediaPlayerService::Client::ServiceDeathNotifier::~ServiceDeathNotifier() {
656 mService->unlinkToDeath(this);
657}
658
659void MediaPlayerService::Client::ServiceDeathNotifier::binderDied(const wp<IBinder>& /*who*/) {
660 sp<MediaPlayerBase> listener = mListener.promote();
661 if (listener != NULL) {
662 listener->sendEvent(MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED, mWhich);
663 } else {
664 ALOGW("listener for process %d death is gone", mWhich);
665 }
666}
667
John Grossmanc795b642012-02-22 15:38:35 -0800668sp<MediaPlayerBase> MediaPlayerService::Client::setDataSource_pre(
669 player_type playerType)
670{
671 ALOGV("player type = %d", playerType);
672
673 // create the right type of player
674 sp<MediaPlayerBase> p = createPlayer(playerType);
675 if (p == NULL) {
676 return p;
677 }
678
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700679 sp<IServiceManager> sm = defaultServiceManager();
680 sp<IBinder> binder = sm->getService(String16("media.extractor"));
681 mExtractorDeathListener = new ServiceDeathNotifier(binder, p, MEDIAEXTRACTOR_PROCESS_DEATH);
682 binder->linkToDeath(mExtractorDeathListener);
683
684 binder = sm->getService(String16("media.codec"));
685 mCodecDeathListener = new ServiceDeathNotifier(binder, p, MEDIACODEC_PROCESS_DEATH);
686 binder->linkToDeath(mCodecDeathListener);
687
John Grossmanc795b642012-02-22 15:38:35 -0800688 if (!p->hardwareOutput()) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -0700689 Mutex::Autolock l(mLock);
Marco Nelissend457c972014-02-11 08:47:07 -0800690 mAudioOutput = new AudioOutput(mAudioSessionId, IPCThreadState::self()->getCallingUid(),
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700691 mPid, mAudioAttributes);
John Grossmanc795b642012-02-22 15:38:35 -0800692 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
693 }
694
695 return p;
696}
697
698void MediaPlayerService::Client::setDataSource_post(
699 const sp<MediaPlayerBase>& p,
700 status_t status)
701{
702 ALOGV(" setDataSource");
703 mStatus = status;
704 if (mStatus != OK) {
705 ALOGE(" error: %d", mStatus);
706 return;
707 }
708
709 // Set the re-transmission endpoint if one was chosen.
710 if (mRetransmitEndpointValid) {
711 mStatus = p->setRetransmitEndpoint(&mRetransmitEndpoint);
712 if (mStatus != NO_ERROR) {
713 ALOGE("setRetransmitEndpoint error: %d", mStatus);
714 }
715 }
716
717 if (mStatus == OK) {
718 mPlayer = p;
719 }
720}
721
Andreas Huber2db84552010-01-28 11:19:57 -0800722status_t MediaPlayerService::Client::setDataSource(
Andreas Huber1b86fe02014-01-29 11:13:26 -0800723 const sp<IMediaHTTPService> &httpService,
724 const char *url,
725 const KeyedVector<String8, String8> *headers)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800726{
Steve Block3856b092011-10-20 11:56:00 +0100727 ALOGV("setDataSource(%s)", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800728 if (url == NULL)
729 return UNKNOWN_ERROR;
730
Dave Burked681bbb2011-08-30 14:39:17 +0100731 if ((strncmp(url, "http://", 7) == 0) ||
732 (strncmp(url, "https://", 8) == 0) ||
733 (strncmp(url, "rtsp://", 7) == 0)) {
734 if (!checkPermission("android.permission.INTERNET")) {
735 return PERMISSION_DENIED;
736 }
737 }
738
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800739 if (strncmp(url, "content://", 10) == 0) {
740 // get a filedescriptor for the content Uri and
741 // pass it to the setDataSource(fd) method
742
743 String16 url16(url);
744 int fd = android::openContentProviderFile(url16);
745 if (fd < 0)
746 {
Steve Block29357bc2012-01-06 19:20:56 +0000747 ALOGE("Couldn't open fd for %s", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800748 return UNKNOWN_ERROR;
749 }
750 setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
751 close(fd);
752 return mStatus;
753 } else {
John Grossman44a7e422012-06-21 17:29:24 -0700754 player_type playerType = MediaPlayerFactory::getPlayerType(this, url);
John Grossmanc795b642012-02-22 15:38:35 -0800755 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
756 if (p == NULL) {
757 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800758 }
759
Andreas Huber1b86fe02014-01-29 11:13:26 -0800760 setDataSource_post(p, p->setDataSource(httpService, url, headers));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800761 return mStatus;
762 }
763}
764
765status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
766{
Marco Nelissen83b0fd92015-09-16 13:48:07 -0700767 ALOGV("setDataSource fd=%d (%s), offset=%lld, length=%lld",
768 fd, nameForFd(fd).c_str(), (long long) offset, (long long) length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800769 struct stat sb;
770 int ret = fstat(fd, &sb);
771 if (ret != 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000772 ALOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800773 return UNKNOWN_ERROR;
774 }
775
Andy Hung833b4752016-04-04 17:15:48 -0700776 ALOGV("st_dev = %llu", static_cast<unsigned long long>(sb.st_dev));
Steve Block3856b092011-10-20 11:56:00 +0100777 ALOGV("st_mode = %u", sb.st_mode);
Mark Salyzyn77342f72014-06-18 16:31:32 -0700778 ALOGV("st_uid = %lu", static_cast<unsigned long>(sb.st_uid));
779 ALOGV("st_gid = %lu", static_cast<unsigned long>(sb.st_gid));
Andy Hung833b4752016-04-04 17:15:48 -0700780 ALOGV("st_size = %llu", static_cast<unsigned long long>(sb.st_size));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800781
782 if (offset >= sb.st_size) {
Steve Block29357bc2012-01-06 19:20:56 +0000783 ALOGE("offset error");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800784 return UNKNOWN_ERROR;
785 }
786 if (offset + length > sb.st_size) {
787 length = sb.st_size - offset;
Andy Hung833b4752016-04-04 17:15:48 -0700788 ALOGV("calculated length = %lld", (long long)length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800789 }
790
John Grossman44a7e422012-06-21 17:29:24 -0700791 player_type playerType = MediaPlayerFactory::getPlayerType(this,
792 fd,
793 offset,
794 length);
John Grossmanc795b642012-02-22 15:38:35 -0800795 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
796 if (p == NULL) {
797 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800798 }
799
800 // now set data source
John Grossmanc795b642012-02-22 15:38:35 -0800801 setDataSource_post(p, p->setDataSource(fd, offset, length));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800802 return mStatus;
803}
804
Andreas Hubere2b10282010-11-23 11:41:34 -0800805status_t MediaPlayerService::Client::setDataSource(
806 const sp<IStreamSource> &source) {
807 // create the right type of player
John Grossman44a7e422012-06-21 17:29:24 -0700808 player_type playerType = MediaPlayerFactory::getPlayerType(this, source);
John Grossmanc795b642012-02-22 15:38:35 -0800809 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
Andreas Hubere2b10282010-11-23 11:41:34 -0800810 if (p == NULL) {
811 return NO_INIT;
812 }
813
Andreas Hubere2b10282010-11-23 11:41:34 -0800814 // now set data source
John Grossmanc795b642012-02-22 15:38:35 -0800815 setDataSource_post(p, p->setDataSource(source));
Andreas Hubere2b10282010-11-23 11:41:34 -0800816 return mStatus;
817}
818
Chris Watkins99f31602015-03-20 13:06:33 -0700819status_t MediaPlayerService::Client::setDataSource(
820 const sp<IDataSource> &source) {
821 sp<DataSource> dataSource = DataSource::CreateFromIDataSource(source);
822 player_type playerType = MediaPlayerFactory::getPlayerType(this, dataSource);
823 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
824 if (p == NULL) {
825 return NO_INIT;
826 }
827 // now set data source
828 setDataSource_post(p, p->setDataSource(dataSource));
829 return mStatus;
830}
831
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700832void MediaPlayerService::Client::disconnectNativeWindow() {
833 if (mConnectedWindow != NULL) {
834 status_t err = native_window_api_disconnect(mConnectedWindow.get(),
835 NATIVE_WINDOW_API_MEDIA);
836
837 if (err != OK) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000838 ALOGW("native_window_api_disconnect returned an error: %s (%d)",
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700839 strerror(-err), err);
840 }
841 }
842 mConnectedWindow.clear();
843}
844
Glenn Kasten11731182011-02-08 17:26:17 -0800845status_t MediaPlayerService::Client::setVideoSurfaceTexture(
Andy McFadden484566c2012-12-18 09:46:54 -0800846 const sp<IGraphicBufferProducer>& bufferProducer)
Glenn Kasten11731182011-02-08 17:26:17 -0800847{
Andy McFadden484566c2012-12-18 09:46:54 -0800848 ALOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, bufferProducer.get());
Glenn Kasten11731182011-02-08 17:26:17 -0800849 sp<MediaPlayerBase> p = getPlayer();
850 if (p == 0) return UNKNOWN_ERROR;
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700851
Marco Nelissenf8880202014-11-14 07:58:25 -0800852 sp<IBinder> binder(IInterface::asBinder(bufferProducer));
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700853 if (mConnectedWindowBinder == binder) {
854 return OK;
855 }
856
857 sp<ANativeWindow> anw;
Andy McFadden484566c2012-12-18 09:46:54 -0800858 if (bufferProducer != NULL) {
Marco Nelissenee08f7e2013-09-16 13:30:01 -0700859 anw = new Surface(bufferProducer, true /* controlledByApp */);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700860 status_t err = native_window_api_connect(anw.get(),
861 NATIVE_WINDOW_API_MEDIA);
862
863 if (err != OK) {
Steve Block29357bc2012-01-06 19:20:56 +0000864 ALOGE("setVideoSurfaceTexture failed: %d", err);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700865 // Note that we must do the reset before disconnecting from the ANW.
866 // Otherwise queue/dequeue calls could be made on the disconnected
867 // ANW, which may result in errors.
868 reset();
869
870 disconnectNativeWindow();
871
872 return err;
873 }
874 }
875
Andy McFadden484566c2012-12-18 09:46:54 -0800876 // Note that we must set the player's new GraphicBufferProducer before
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700877 // disconnecting the old one. Otherwise queue/dequeue calls could be made
878 // on the disconnected ANW, which may result in errors.
Andy McFadden484566c2012-12-18 09:46:54 -0800879 status_t err = p->setVideoSurfaceTexture(bufferProducer);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700880
881 disconnectNativeWindow();
882
883 mConnectedWindow = anw;
884
885 if (err == OK) {
886 mConnectedWindowBinder = binder;
887 } else {
888 disconnectNativeWindow();
889 }
890
891 return err;
Glenn Kasten11731182011-02-08 17:26:17 -0800892}
893
Nicolas Catania1d187f12009-05-12 23:25:55 -0700894status_t MediaPlayerService::Client::invoke(const Parcel& request,
895 Parcel *reply)
896{
897 sp<MediaPlayerBase> p = getPlayer();
898 if (p == NULL) return UNKNOWN_ERROR;
899 return p->invoke(request, reply);
900}
901
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700902// This call doesn't need to access the native player.
903status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
904{
905 status_t status;
nikoa64c8c72009-07-20 15:07:26 -0700906 media::Metadata::Filter allow, drop;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700907
Nicolas Catania48290382009-07-10 13:53:06 -0700908 if (unmarshallFilter(filter, &allow, &status) &&
909 unmarshallFilter(filter, &drop, &status)) {
910 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700911
912 mMetadataAllow = allow;
913 mMetadataDrop = drop;
914 }
915 return status;
916}
917
Nicolas Catania48290382009-07-10 13:53:06 -0700918status_t MediaPlayerService::Client::getMetadata(
Mark Salyzyn77342f72014-06-18 16:31:32 -0700919 bool update_only, bool /*apply_filter*/, Parcel *reply)
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700920{
nikoa64c8c72009-07-20 15:07:26 -0700921 sp<MediaPlayerBase> player = getPlayer();
922 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania48290382009-07-10 13:53:06 -0700923
nikod608a812009-07-16 16:39:53 -0700924 status_t status;
925 // Placeholder for the return code, updated by the caller.
926 reply->writeInt32(-1);
927
nikoa64c8c72009-07-20 15:07:26 -0700928 media::Metadata::Filter ids;
Nicolas Catania48290382009-07-10 13:53:06 -0700929
930 // We don't block notifications while we fetch the data. We clear
931 // mMetadataUpdated first so we don't lose notifications happening
932 // during the rest of this call.
933 {
934 Mutex::Autolock lock(mLock);
935 if (update_only) {
nikod608a812009-07-16 16:39:53 -0700936 ids = mMetadataUpdated;
Nicolas Catania48290382009-07-10 13:53:06 -0700937 }
938 mMetadataUpdated.clear();
939 }
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700940
nikoa64c8c72009-07-20 15:07:26 -0700941 media::Metadata metadata(reply);
Nicolas Catania48290382009-07-10 13:53:06 -0700942
nikoa64c8c72009-07-20 15:07:26 -0700943 metadata.appendHeader();
944 status = player->getMetadata(ids, reply);
nikod608a812009-07-16 16:39:53 -0700945
946 if (status != OK) {
nikoa64c8c72009-07-20 15:07:26 -0700947 metadata.resetParcel();
Steve Block29357bc2012-01-06 19:20:56 +0000948 ALOGE("getMetadata failed %d", status);
nikod608a812009-07-16 16:39:53 -0700949 return status;
950 }
951
952 // FIXME: Implement filtering on the result. Not critical since
953 // filtering takes place on the update notifications already. This
954 // would be when all the metadata are fetch and a filter is set.
955
nikod608a812009-07-16 16:39:53 -0700956 // Everything is fine, update the metadata length.
nikoa64c8c72009-07-20 15:07:26 -0700957 metadata.updateLength();
nikod608a812009-07-16 16:39:53 -0700958 return OK;
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700959}
960
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800961status_t MediaPlayerService::Client::prepareAsync()
962{
Steve Block3856b092011-10-20 11:56:00 +0100963 ALOGV("[%d] prepareAsync", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800964 sp<MediaPlayerBase> p = getPlayer();
965 if (p == 0) return UNKNOWN_ERROR;
966 status_t ret = p->prepareAsync();
967#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000968 ALOGD("start Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800969 if (ret == NO_ERROR) mAntagonizer->start();
970#endif
971 return ret;
972}
973
974status_t MediaPlayerService::Client::start()
975{
Steve Block3856b092011-10-20 11:56:00 +0100976 ALOGV("[%d] start", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800977 sp<MediaPlayerBase> p = getPlayer();
978 if (p == 0) return UNKNOWN_ERROR;
979 p->setLooping(mLoop);
980 return p->start();
981}
982
983status_t MediaPlayerService::Client::stop()
984{
Steve Block3856b092011-10-20 11:56:00 +0100985 ALOGV("[%d] stop", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800986 sp<MediaPlayerBase> p = getPlayer();
987 if (p == 0) return UNKNOWN_ERROR;
988 return p->stop();
989}
990
991status_t MediaPlayerService::Client::pause()
992{
Steve Block3856b092011-10-20 11:56:00 +0100993 ALOGV("[%d] pause", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800994 sp<MediaPlayerBase> p = getPlayer();
995 if (p == 0) return UNKNOWN_ERROR;
996 return p->pause();
997}
998
999status_t MediaPlayerService::Client::isPlaying(bool* state)
1000{
1001 *state = false;
1002 sp<MediaPlayerBase> p = getPlayer();
1003 if (p == 0) return UNKNOWN_ERROR;
1004 *state = p->isPlaying();
Steve Block3856b092011-10-20 11:56:00 +01001005 ALOGV("[%d] isPlaying: %d", mConnId, *state);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001006 return NO_ERROR;
1007}
1008
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001009status_t MediaPlayerService::Client::setPlaybackSettings(const AudioPlaybackRate& rate)
Wei Jia98160162015-02-04 17:01:11 -08001010{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001011 ALOGV("[%d] setPlaybackSettings(%f, %f, %d, %d)",
1012 mConnId, rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Wei Jia98160162015-02-04 17:01:11 -08001013 sp<MediaPlayerBase> p = getPlayer();
1014 if (p == 0) return UNKNOWN_ERROR;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001015 return p->setPlaybackSettings(rate);
1016}
1017
1018status_t MediaPlayerService::Client::getPlaybackSettings(AudioPlaybackRate* rate /* nonnull */)
1019{
1020 sp<MediaPlayerBase> p = getPlayer();
1021 if (p == 0) return UNKNOWN_ERROR;
1022 status_t ret = p->getPlaybackSettings(rate);
1023 if (ret == NO_ERROR) {
1024 ALOGV("[%d] getPlaybackSettings(%f, %f, %d, %d)",
1025 mConnId, rate->mSpeed, rate->mPitch, rate->mFallbackMode, rate->mStretchMode);
1026 } else {
1027 ALOGV("[%d] getPlaybackSettings returned %d", mConnId, ret);
1028 }
1029 return ret;
1030}
1031
1032status_t MediaPlayerService::Client::setSyncSettings(
1033 const AVSyncSettings& sync, float videoFpsHint)
1034{
1035 ALOGV("[%d] setSyncSettings(%u, %u, %f, %f)",
1036 mConnId, sync.mSource, sync.mAudioAdjustMode, sync.mTolerance, videoFpsHint);
1037 sp<MediaPlayerBase> p = getPlayer();
1038 if (p == 0) return UNKNOWN_ERROR;
1039 return p->setSyncSettings(sync, videoFpsHint);
1040}
1041
1042status_t MediaPlayerService::Client::getSyncSettings(
1043 AVSyncSettings* sync /* nonnull */, float* videoFps /* nonnull */)
1044{
1045 sp<MediaPlayerBase> p = getPlayer();
1046 if (p == 0) return UNKNOWN_ERROR;
1047 status_t ret = p->getSyncSettings(sync, videoFps);
1048 if (ret == NO_ERROR) {
1049 ALOGV("[%d] getSyncSettings(%u, %u, %f, %f)",
1050 mConnId, sync->mSource, sync->mAudioAdjustMode, sync->mTolerance, *videoFps);
1051 } else {
1052 ALOGV("[%d] getSyncSettings returned %d", mConnId, ret);
1053 }
1054 return ret;
Wei Jia98160162015-02-04 17:01:11 -08001055}
1056
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001057status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
1058{
Steve Block3856b092011-10-20 11:56:00 +01001059 ALOGV("getCurrentPosition");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001060 sp<MediaPlayerBase> p = getPlayer();
1061 if (p == 0) return UNKNOWN_ERROR;
1062 status_t ret = p->getCurrentPosition(msec);
1063 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001064 ALOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001065 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001066 ALOGE("getCurrentPosition returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001067 }
1068 return ret;
1069}
1070
1071status_t MediaPlayerService::Client::getDuration(int *msec)
1072{
Steve Block3856b092011-10-20 11:56:00 +01001073 ALOGV("getDuration");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001074 sp<MediaPlayerBase> p = getPlayer();
1075 if (p == 0) return UNKNOWN_ERROR;
1076 status_t ret = p->getDuration(msec);
1077 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001078 ALOGV("[%d] getDuration = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001079 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001080 ALOGE("getDuration returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001081 }
1082 return ret;
1083}
1084
Marco Nelissen6b74d672012-02-28 16:07:44 -08001085status_t MediaPlayerService::Client::setNextPlayer(const sp<IMediaPlayer>& player) {
1086 ALOGV("setNextPlayer");
1087 Mutex::Autolock l(mLock);
1088 sp<Client> c = static_cast<Client*>(player.get());
1089 mNextClient = c;
John Grossman5f7e55e2012-08-24 14:47:25 -07001090
1091 if (c != NULL) {
1092 if (mAudioOutput != NULL) {
1093 mAudioOutput->setNextOutput(c->mAudioOutput);
1094 } else if ((mPlayer != NULL) && !mPlayer->hardwareOutput()) {
1095 ALOGE("no current audio output");
1096 }
1097
1098 if ((mPlayer != NULL) && (mNextClient->getPlayer() != NULL)) {
1099 mPlayer->setNextPlayer(mNextClient->getPlayer());
1100 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001101 }
John Grossman5f7e55e2012-08-24 14:47:25 -07001102
Marco Nelissen6b74d672012-02-28 16:07:44 -08001103 return OK;
1104}
1105
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001106status_t MediaPlayerService::Client::seekTo(int msec)
1107{
Steve Block3856b092011-10-20 11:56:00 +01001108 ALOGV("[%d] seekTo(%d)", mConnId, msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001109 sp<MediaPlayerBase> p = getPlayer();
1110 if (p == 0) return UNKNOWN_ERROR;
1111 return p->seekTo(msec);
1112}
1113
1114status_t MediaPlayerService::Client::reset()
1115{
Steve Block3856b092011-10-20 11:56:00 +01001116 ALOGV("[%d] reset", mConnId);
John Grossmanc795b642012-02-22 15:38:35 -08001117 mRetransmitEndpointValid = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001118 sp<MediaPlayerBase> p = getPlayer();
1119 if (p == 0) return UNKNOWN_ERROR;
1120 return p->reset();
1121}
1122
Glenn Kastenfff6d712012-01-12 16:38:12 -08001123status_t MediaPlayerService::Client::setAudioStreamType(audio_stream_type_t type)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001124{
Steve Block3856b092011-10-20 11:56:00 +01001125 ALOGV("[%d] setAudioStreamType(%d)", mConnId, type);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001126 // TODO: for hardware output, call player instead
1127 Mutex::Autolock l(mLock);
1128 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1129 return NO_ERROR;
1130}
1131
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001132status_t MediaPlayerService::Client::setAudioAttributes_l(const Parcel &parcel)
1133{
1134 if (mAudioAttributes != NULL) { free(mAudioAttributes); }
1135 mAudioAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001136 if (mAudioAttributes == NULL) {
1137 return NO_MEMORY;
1138 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001139 unmarshallAudioAttributes(parcel, mAudioAttributes);
1140
1141 ALOGV("setAudioAttributes_l() usage=%d content=%d flags=0x%x tags=%s",
1142 mAudioAttributes->usage, mAudioAttributes->content_type, mAudioAttributes->flags,
1143 mAudioAttributes->tags);
1144
1145 if (mAudioOutput != 0) {
1146 mAudioOutput->setAudioAttributes(mAudioAttributes);
1147 }
1148 return NO_ERROR;
1149}
1150
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001151status_t MediaPlayerService::Client::setLooping(int loop)
1152{
Steve Block3856b092011-10-20 11:56:00 +01001153 ALOGV("[%d] setLooping(%d)", mConnId, loop);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001154 mLoop = loop;
1155 sp<MediaPlayerBase> p = getPlayer();
1156 if (p != 0) return p->setLooping(loop);
1157 return NO_ERROR;
1158}
1159
1160status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1161{
Steve Block3856b092011-10-20 11:56:00 +01001162 ALOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
John Grossman761defc2012-02-09 15:09:05 -08001163
1164 // for hardware output, call player instead
1165 sp<MediaPlayerBase> p = getPlayer();
1166 {
1167 Mutex::Autolock l(mLock);
1168 if (p != 0 && p->hardwareOutput()) {
1169 MediaPlayerHWInterface* hwp =
1170 reinterpret_cast<MediaPlayerHWInterface*>(p.get());
1171 return hwp->setVolume(leftVolume, rightVolume);
1172 } else {
1173 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1174 return NO_ERROR;
1175 }
1176 }
1177
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001178 return NO_ERROR;
1179}
1180
Eric Laurent2beeb502010-07-16 07:43:46 -07001181status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1182{
Steve Block3856b092011-10-20 11:56:00 +01001183 ALOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
Eric Laurent2beeb502010-07-16 07:43:46 -07001184 Mutex::Autolock l(mLock);
1185 if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1186 return NO_ERROR;
1187}
1188
1189status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1190{
Steve Block3856b092011-10-20 11:56:00 +01001191 ALOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
Eric Laurent2beeb502010-07-16 07:43:46 -07001192 Mutex::Autolock l(mLock);
1193 if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1194 return NO_ERROR;
1195}
Nicolas Catania48290382009-07-10 13:53:06 -07001196
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001197status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
Steve Block3856b092011-10-20 11:56:00 +01001198 ALOGV("[%d] setParameter(%d)", mConnId, key);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001199 switch (key) {
1200 case KEY_PARAMETER_AUDIO_ATTRIBUTES:
1201 {
1202 Mutex::Autolock l(mLock);
1203 return setAudioAttributes_l(request);
1204 }
1205 default:
1206 sp<MediaPlayerBase> p = getPlayer();
1207 if (p == 0) { return UNKNOWN_ERROR; }
1208 return p->setParameter(key, request);
1209 }
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001210}
1211
1212status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
Steve Block3856b092011-10-20 11:56:00 +01001213 ALOGV("[%d] getParameter(%d)", mConnId, key);
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001214 sp<MediaPlayerBase> p = getPlayer();
1215 if (p == 0) return UNKNOWN_ERROR;
1216 return p->getParameter(key, reply);
1217}
1218
John Grossmanc795b642012-02-22 15:38:35 -08001219status_t MediaPlayerService::Client::setRetransmitEndpoint(
1220 const struct sockaddr_in* endpoint) {
1221
1222 if (NULL != endpoint) {
1223 uint32_t a = ntohl(endpoint->sin_addr.s_addr);
1224 uint16_t p = ntohs(endpoint->sin_port);
1225 ALOGV("[%d] setRetransmitEndpoint(%u.%u.%u.%u:%hu)", mConnId,
1226 (a >> 24), (a >> 16) & 0xFF, (a >> 8) & 0xFF, (a & 0xFF), p);
1227 } else {
1228 ALOGV("[%d] setRetransmitEndpoint = <none>", mConnId);
1229 }
1230
1231 sp<MediaPlayerBase> p = getPlayer();
1232
1233 // Right now, the only valid time to set a retransmit endpoint is before
1234 // player selection has been made (since the presence or absence of a
1235 // retransmit endpoint is going to determine which player is selected during
1236 // setDataSource).
1237 if (p != 0) return INVALID_OPERATION;
1238
1239 if (NULL != endpoint) {
1240 mRetransmitEndpoint = *endpoint;
1241 mRetransmitEndpointValid = true;
1242 } else {
1243 mRetransmitEndpointValid = false;
1244 }
1245
1246 return NO_ERROR;
1247}
1248
John Grossman44a7e422012-06-21 17:29:24 -07001249status_t MediaPlayerService::Client::getRetransmitEndpoint(
1250 struct sockaddr_in* endpoint)
1251{
1252 if (NULL == endpoint)
1253 return BAD_VALUE;
1254
1255 sp<MediaPlayerBase> p = getPlayer();
1256
1257 if (p != NULL)
1258 return p->getRetransmitEndpoint(endpoint);
1259
1260 if (!mRetransmitEndpointValid)
1261 return NO_INIT;
1262
1263 *endpoint = mRetransmitEndpoint;
1264
1265 return NO_ERROR;
1266}
1267
Gloria Wangb483c472011-04-11 17:23:27 -07001268void MediaPlayerService::Client::notify(
1269 void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001270{
1271 Client* client = static_cast<Client*>(cookie);
James Dongb8a98252012-08-26 16:13:03 -07001272 if (client == NULL) {
1273 return;
1274 }
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001275
James Dongb8a98252012-08-26 16:13:03 -07001276 sp<IMediaPlayerClient> c;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001277 {
1278 Mutex::Autolock l(client->mLock);
James Dongb8a98252012-08-26 16:13:03 -07001279 c = client->mClient;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001280 if (msg == MEDIA_PLAYBACK_COMPLETE && client->mNextClient != NULL) {
John Grossmancb0b7552012-08-23 17:47:31 -07001281 if (client->mAudioOutput != NULL)
1282 client->mAudioOutput->switchToNextOutput();
Marco Nelissen6b74d672012-02-28 16:07:44 -08001283 client->mNextClient->start();
Wei Jia2afac0c2016-01-07 12:13:07 -08001284 if (client->mNextClient->mClient != NULL) {
1285 client->mNextClient->mClient->notify(
1286 MEDIA_INFO, MEDIA_INFO_STARTED_AS_NEXT, 0, obj);
1287 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001288 }
1289 }
1290
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001291 if (MEDIA_INFO == msg &&
Nicolas Catania48290382009-07-10 13:53:06 -07001292 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikoa64c8c72009-07-20 15:07:26 -07001293 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania48290382009-07-10 13:53:06 -07001294
1295 if(client->shouldDropMetadata(metadata_type)) {
1296 return;
1297 }
1298
1299 // Update the list of metadata that have changed. getMetadata
1300 // also access mMetadataUpdated and clears it.
1301 client->addNewMetadataUpdate(metadata_type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001302 }
James Dongb8a98252012-08-26 16:13:03 -07001303
1304 if (c != NULL) {
1305 ALOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
1306 c->notify(msg, ext1, ext2, obj);
1307 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001308}
1309
Nicolas Catania48290382009-07-10 13:53:06 -07001310
nikoa64c8c72009-07-20 15:07:26 -07001311bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001312{
Nicolas Catania48290382009-07-10 13:53:06 -07001313 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001314
Nicolas Catania48290382009-07-10 13:53:06 -07001315 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001316 return true;
1317 }
1318
Nicolas Catania48290382009-07-10 13:53:06 -07001319 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001320 return false;
Nicolas Catania48290382009-07-10 13:53:06 -07001321 } else {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001322 return true;
1323 }
1324}
1325
Nicolas Catania48290382009-07-10 13:53:06 -07001326
nikoa64c8c72009-07-20 15:07:26 -07001327void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania48290382009-07-10 13:53:06 -07001328 Mutex::Autolock lock(mLock);
1329 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1330 mMetadataUpdated.add(metadata_type);
1331 }
1332}
1333
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001334#if CALLBACK_ANTAGONIZER
1335const int Antagonizer::interval = 10000; // 10 msecs
1336
1337Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1338 mExit(false), mActive(false), mClient(client), mCb(cb)
1339{
1340 createThread(callbackThread, this);
1341}
1342
1343void Antagonizer::kill()
1344{
1345 Mutex::Autolock _l(mLock);
1346 mActive = false;
1347 mExit = true;
1348 mCondition.wait(mLock);
1349}
1350
1351int Antagonizer::callbackThread(void* user)
1352{
Steve Blockb8a80522011-12-20 16:23:08 +00001353 ALOGD("Antagonizer started");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001354 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1355 while (!p->mExit) {
1356 if (p->mActive) {
Steve Block3856b092011-10-20 11:56:00 +01001357 ALOGV("send event");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001358 p->mCb(p->mClient, 0, 0, 0);
1359 }
1360 usleep(interval);
1361 }
1362 Mutex::Autolock _l(p->mLock);
1363 p->mCondition.signal();
Steve Blockb8a80522011-12-20 16:23:08 +00001364 ALOGD("Antagonizer stopped");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001365 return 0;
1366}
1367#endif
1368
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001369#undef LOG_TAG
1370#define LOG_TAG "AudioSink"
Glenn Kastend848eb42016-03-08 13:42:11 -08001371MediaPlayerService::AudioOutput::AudioOutput(audio_session_t sessionId, int uid, int pid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001372 const audio_attributes_t* attr)
Andreas Huber20111aa2009-07-14 16:56:47 -07001373 : mCallback(NULL),
Eric Laurenta514bdb2010-06-21 09:27:30 -07001374 mCallbackCookie(NULL),
Marco Nelissen6b74d672012-02-28 16:07:44 -08001375 mCallbackData(NULL),
Andy Hungd1c74342015-07-07 16:54:23 -07001376 mStreamType(AUDIO_STREAM_MUSIC),
Andy Hungd1c74342015-07-07 16:54:23 -07001377 mLeftVolume(1.0),
1378 mRightVolume(1.0),
1379 mPlaybackRate(AUDIO_PLAYBACK_RATE_DEFAULT),
1380 mSampleRateHz(0),
1381 mMsecsPerFrame(0),
1382 mFrameSize(0),
Eric Laurent1948eb32012-04-13 16:50:19 -07001383 mSessionId(sessionId),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001384 mUid(uid),
Marco Nelissend457c972014-02-11 08:47:07 -08001385 mPid(pid),
Andy Hungd1c74342015-07-07 16:54:23 -07001386 mSendLevel(0.0),
1387 mAuxEffectId(0),
1388 mFlags(AUDIO_OUTPUT_FLAG_NONE)
1389{
Steve Block3856b092011-10-20 11:56:00 +01001390 ALOGV("AudioOutput(%d)", sessionId);
Eric Laurent43562692015-07-15 16:49:07 -07001391 if (attr != NULL) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001392 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1393 if (mAttributes != NULL) {
1394 memcpy(mAttributes, attr, sizeof(audio_attributes_t));
1395 mStreamType = audio_attributes_to_stream_type(attr);
1396 }
1397 } else {
1398 mAttributes = NULL;
Eric Laurent43562692015-07-15 16:49:07 -07001399 }
1400
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001401 setMinBufferCount();
1402}
1403
1404MediaPlayerService::AudioOutput::~AudioOutput()
1405{
1406 close();
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001407 free(mAttributes);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001408 delete mCallbackData;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001409}
1410
Andy Hungd1c74342015-07-07 16:54:23 -07001411//static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001412void MediaPlayerService::AudioOutput::setMinBufferCount()
1413{
1414 char value[PROPERTY_VALUE_MAX];
1415 if (property_get("ro.kernel.qemu", value, 0)) {
1416 mIsOnEmulator = true;
1417 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1418 }
1419}
1420
Andy Hungd1c74342015-07-07 16:54:23 -07001421// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001422bool MediaPlayerService::AudioOutput::isOnEmulator()
1423{
Andy Hungd1c74342015-07-07 16:54:23 -07001424 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001425 return mIsOnEmulator;
1426}
1427
Andy Hungd1c74342015-07-07 16:54:23 -07001428// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001429int MediaPlayerService::AudioOutput::getMinBufferCount()
1430{
Andy Hungd1c74342015-07-07 16:54:23 -07001431 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001432 return mMinBufferCount;
1433}
1434
1435ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1436{
Andy Hungd1c74342015-07-07 16:54:23 -07001437 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001438 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001439 return mTrack->frameCount() * mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001440}
1441
1442ssize_t MediaPlayerService::AudioOutput::frameCount() const
1443{
Andy Hungd1c74342015-07-07 16:54:23 -07001444 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001445 if (mTrack == 0) return NO_INIT;
1446 return mTrack->frameCount();
1447}
1448
1449ssize_t MediaPlayerService::AudioOutput::channelCount() const
1450{
Andy Hungd1c74342015-07-07 16:54:23 -07001451 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001452 if (mTrack == 0) return NO_INIT;
1453 return mTrack->channelCount();
1454}
1455
1456ssize_t MediaPlayerService::AudioOutput::frameSize() const
1457{
Andy Hungd1c74342015-07-07 16:54:23 -07001458 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001459 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001460 return mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001461}
1462
1463uint32_t MediaPlayerService::AudioOutput::latency () const
1464{
Andy Hungd1c74342015-07-07 16:54:23 -07001465 Mutex::Autolock lock(mLock);
Eric Laurentdb354e52012-03-05 17:27:11 -08001466 if (mTrack == 0) return 0;
1467 return mTrack->latency();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001468}
1469
1470float MediaPlayerService::AudioOutput::msecsPerFrame() const
1471{
Andy Hungd1c74342015-07-07 16:54:23 -07001472 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001473 return mMsecsPerFrame;
1474}
1475
Marco Nelissen4110c102012-03-29 09:31:28 -07001476status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position) const
Eric Laurent342e9cf2010-01-19 17:37:09 -08001477{
Andy Hungd1c74342015-07-07 16:54:23 -07001478 Mutex::Autolock lock(mLock);
Eric Laurent342e9cf2010-01-19 17:37:09 -08001479 if (mTrack == 0) return NO_INIT;
1480 return mTrack->getPosition(position);
1481}
1482
Lajos Molnar06ad1522014-08-28 07:27:44 -07001483status_t MediaPlayerService::AudioOutput::getTimestamp(AudioTimestamp &ts) const
1484{
Andy Hungd1c74342015-07-07 16:54:23 -07001485 Mutex::Autolock lock(mLock);
Lajos Molnar06ad1522014-08-28 07:27:44 -07001486 if (mTrack == 0) return NO_INIT;
1487 return mTrack->getTimestamp(ts);
1488}
1489
Wei Jiac4ac8172015-10-21 10:35:48 -07001490// TODO: Remove unnecessary calls to getPlayedOutDurationUs()
1491// as it acquires locks and may query the audio driver.
1492//
1493// Some calls could conceivably retrieve extrapolated data instead of
1494// accessing getTimestamp() or getPosition() every time a data buffer with
1495// a media time is received.
1496//
1497// Calculate duration of played samples if played at normal rate (i.e., 1.0).
1498int64_t MediaPlayerService::AudioOutput::getPlayedOutDurationUs(int64_t nowUs) const
1499{
1500 Mutex::Autolock lock(mLock);
1501 if (mTrack == 0 || mSampleRateHz == 0) {
Wei Jia213f4902015-10-22 08:55:25 -07001502 return 0;
Wei Jiac4ac8172015-10-21 10:35:48 -07001503 }
1504
1505 uint32_t numFramesPlayed;
1506 int64_t numFramesPlayedAt;
1507 AudioTimestamp ts;
1508 static const int64_t kStaleTimestamp100ms = 100000;
1509
1510 status_t res = mTrack->getTimestamp(ts);
1511 if (res == OK) { // case 1: mixing audio tracks and offloaded tracks.
1512 numFramesPlayed = ts.mPosition;
1513 numFramesPlayedAt = ts.mTime.tv_sec * 1000000LL + ts.mTime.tv_nsec / 1000;
1514 const int64_t timestampAge = nowUs - numFramesPlayedAt;
1515 if (timestampAge > kStaleTimestamp100ms) {
1516 // This is an audio FIXME.
1517 // getTimestamp returns a timestamp which may come from audio mixing threads.
1518 // After pausing, the MixerThread may go idle, thus the mTime estimate may
1519 // become stale. Assuming that the MixerThread runs 20ms, with FastMixer at 5ms,
1520 // the max latency should be about 25ms with an average around 12ms (to be verified).
1521 // For safety we use 100ms.
1522 ALOGV("getTimestamp: returned stale timestamp nowUs(%lld) numFramesPlayedAt(%lld)",
1523 (long long)nowUs, (long long)numFramesPlayedAt);
1524 numFramesPlayedAt = nowUs - kStaleTimestamp100ms;
1525 }
1526 //ALOGD("getTimestamp: OK %d %lld", numFramesPlayed, (long long)numFramesPlayedAt);
1527 } else if (res == WOULD_BLOCK) { // case 2: transitory state on start of a new track
1528 numFramesPlayed = 0;
1529 numFramesPlayedAt = nowUs;
1530 //ALOGD("getTimestamp: WOULD_BLOCK %d %lld",
1531 // numFramesPlayed, (long long)numFramesPlayedAt);
1532 } else { // case 3: transitory at new track or audio fast tracks.
1533 res = mTrack->getPosition(&numFramesPlayed);
1534 CHECK_EQ(res, (status_t)OK);
1535 numFramesPlayedAt = nowUs;
1536 numFramesPlayedAt += 1000LL * mTrack->latency() / 2; /* XXX */
1537 //ALOGD("getPosition: %u %lld", numFramesPlayed, (long long)numFramesPlayedAt);
1538 }
1539
1540 // CHECK_EQ(numFramesPlayed & (1 << 31), 0); // can't be negative until 12.4 hrs, test
1541 // TODO: remove the (int32_t) casting below as it may overflow at 12.4 hours.
1542 int64_t durationUs = (int64_t)((int32_t)numFramesPlayed * 1000000LL / mSampleRateHz)
1543 + nowUs - numFramesPlayedAt;
1544 if (durationUs < 0) {
1545 // Occurs when numFramesPlayed position is very small and the following:
1546 // (1) In case 1, the time nowUs is computed before getTimestamp() is called and
1547 // numFramesPlayedAt is greater than nowUs by time more than numFramesPlayed.
1548 // (2) In case 3, using getPosition and adding mAudioSink->latency() to
1549 // numFramesPlayedAt, by a time amount greater than numFramesPlayed.
1550 //
1551 // Both of these are transitory conditions.
1552 ALOGV("getPlayedOutDurationUs: negative duration %lld set to zero", (long long)durationUs);
1553 durationUs = 0;
1554 }
1555 ALOGV("getPlayedOutDurationUs(%lld) nowUs(%lld) frames(%u) framesAt(%lld)",
1556 (long long)durationUs, (long long)nowUs, numFramesPlayed, (long long)numFramesPlayedAt);
1557 return durationUs;
1558}
1559
Marco Nelissen4110c102012-03-29 09:31:28 -07001560status_t MediaPlayerService::AudioOutput::getFramesWritten(uint32_t *frameswritten) const
1561{
Andy Hungd1c74342015-07-07 16:54:23 -07001562 Mutex::Autolock lock(mLock);
Marco Nelissen4110c102012-03-29 09:31:28 -07001563 if (mTrack == 0) return NO_INIT;
Andy Hung2f6e73d2016-04-08 12:12:58 -07001564 ExtendedTimestamp ets;
1565 status_t status = mTrack->getTimestamp(&ets);
1566 if (status == OK || status == WOULD_BLOCK) {
1567 *frameswritten = (uint32_t)ets.mPosition[ExtendedTimestamp::LOCATION_CLIENT];
1568 }
1569 return status;
Marco Nelissen4110c102012-03-29 09:31:28 -07001570}
1571
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001572status_t MediaPlayerService::AudioOutput::setParameters(const String8& keyValuePairs)
1573{
Andy Hungd1c74342015-07-07 16:54:23 -07001574 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001575 if (mTrack == 0) return NO_INIT;
1576 return mTrack->setParameters(keyValuePairs);
1577}
1578
1579String8 MediaPlayerService::AudioOutput::getParameters(const String8& keys)
1580{
Andy Hungd1c74342015-07-07 16:54:23 -07001581 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001582 if (mTrack == 0) return String8::empty();
1583 return mTrack->getParameters(keys);
1584}
1585
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001586void MediaPlayerService::AudioOutput::setAudioAttributes(const audio_attributes_t * attributes) {
Andy Hungd1c74342015-07-07 16:54:23 -07001587 Mutex::Autolock lock(mLock);
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001588 if (attributes == NULL) {
1589 free(mAttributes);
1590 mAttributes = NULL;
1591 } else {
1592 if (mAttributes == NULL) {
1593 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1594 }
1595 memcpy(mAttributes, attributes, sizeof(audio_attributes_t));
Eric Laurent43562692015-07-15 16:49:07 -07001596 mStreamType = audio_attributes_to_stream_type(attributes);
1597 }
1598}
1599
1600void MediaPlayerService::AudioOutput::setAudioStreamType(audio_stream_type_t streamType)
1601{
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001602 Mutex::Autolock lock(mLock);
Eric Laurent43562692015-07-15 16:49:07 -07001603 // do not allow direct stream type modification if attributes have been set
1604 if (mAttributes == NULL) {
1605 mStreamType = streamType;
1606 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001607}
1608
Andy Hungd1c74342015-07-07 16:54:23 -07001609void MediaPlayerService::AudioOutput::deleteRecycledTrack_l()
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001610{
Andy Hungd1c74342015-07-07 16:54:23 -07001611 ALOGV("deleteRecycledTrack_l");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001612 if (mRecycledTrack != 0) {
1613
1614 if (mCallbackData != NULL) {
1615 mCallbackData->setOutput(NULL);
1616 mCallbackData->endTrackSwitch();
1617 }
1618
1619 if ((mRecycledTrack->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) {
Andy Hunge13f8a62016-03-30 14:20:42 -07001620 int32_t msec = 0;
1621 if (!mRecycledTrack->stopped()) { // check if active
1622 (void)mRecycledTrack->pendingDuration(&msec);
1623 }
1624 mRecycledTrack->stop(); // ensure full data drain
1625 ALOGD("deleting recycled track, waiting for data drain (%d msec)", msec);
1626 if (msec > 0) {
1627 static const int32_t WAIT_LIMIT_MS = 3000;
1628 if (msec > WAIT_LIMIT_MS) {
1629 msec = WAIT_LIMIT_MS;
1630 }
1631 usleep(msec * 1000LL);
1632 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001633 }
1634 // An offloaded track isn't flushed because the STREAM_END is reported
1635 // slightly prematurely to allow time for the gapless track switch
1636 // but this means that if we decide not to recycle the track there
1637 // could be a small amount of residual data still playing. We leave
1638 // AudioFlinger to drain the track.
1639
1640 mRecycledTrack.clear();
Andy Hungd1c74342015-07-07 16:54:23 -07001641 close_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001642 delete mCallbackData;
1643 mCallbackData = NULL;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001644 }
1645}
1646
Andy Hungd1c74342015-07-07 16:54:23 -07001647void MediaPlayerService::AudioOutput::close_l()
1648{
1649 mTrack.clear();
1650}
1651
Andreas Huber20111aa2009-07-14 16:56:47 -07001652status_t MediaPlayerService::AudioOutput::open(
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001653 uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
1654 audio_format_t format, int bufferCount,
Eric Laurent1948eb32012-04-13 16:50:19 -07001655 AudioCallback cb, void *cookie,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001656 audio_output_flags_t flags,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001657 const audio_offload_info_t *offloadInfo,
Andy Hung179652e2015-05-31 22:49:46 -07001658 bool doNotReconnect,
1659 uint32_t suggestedFrameCount)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001660{
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001661 ALOGV("open(%u, %d, 0x%x, 0x%x, %d, %d 0x%x)", sampleRate, channelCount, channelMask,
1662 format, bufferCount, mSessionId, flags);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001663
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001664 // offloading is only supported in callback mode for now.
1665 // offloadInfo must be present if offload flag is set
1666 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) &&
1667 ((cb == NULL) || (offloadInfo == NULL))) {
1668 return BAD_VALUE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001669 }
1670
Andy Hung179652e2015-05-31 22:49:46 -07001671 // compute frame count for the AudioTrack internal buffer
1672 size_t frameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001673 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1674 frameCount = 0; // AudioTrack will get frame count from AudioFlinger
1675 } else {
Andy Hung179652e2015-05-31 22:49:46 -07001676 // try to estimate the buffer processing fetch size from AudioFlinger.
1677 // framesPerBuffer is approximate and generally correct, except when it's not :-).
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001678 uint32_t afSampleRate;
1679 size_t afFrameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001680 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1681 return NO_INIT;
1682 }
1683 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1684 return NO_INIT;
1685 }
Andy Hung179652e2015-05-31 22:49:46 -07001686 const size_t framesPerBuffer =
1687 (unsigned long long)sampleRate * afFrameCount / afSampleRate;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001688
Andy Hung179652e2015-05-31 22:49:46 -07001689 if (bufferCount == 0) {
1690 // use suggestedFrameCount
1691 bufferCount = (suggestedFrameCount + framesPerBuffer - 1) / framesPerBuffer;
1692 }
1693 // Check argument bufferCount against the mininum buffer count
1694 if (bufferCount != 0 && bufferCount < mMinBufferCount) {
1695 ALOGV("bufferCount (%d) increased to %d", bufferCount, mMinBufferCount);
1696 bufferCount = mMinBufferCount;
1697 }
1698 // if frameCount is 0, then AudioTrack will get frame count from AudioFlinger
1699 // which will be the minimum size permitted.
1700 frameCount = bufferCount * framesPerBuffer;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001701 }
Andreas Huber20111aa2009-07-14 16:56:47 -07001702
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001703 if (channelMask == CHANNEL_MASK_USE_CHANNEL_ORDER) {
Glenn Kastenab334fd2012-03-14 12:56:06 -07001704 channelMask = audio_channel_out_mask_from_count(channelCount);
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001705 if (0 == channelMask) {
1706 ALOGE("open() error, can\'t derive mask for %d audio channels", channelCount);
1707 return NO_INIT;
1708 }
1709 }
Eric Laurent1948eb32012-04-13 16:50:19 -07001710
Andy Hungd1c74342015-07-07 16:54:23 -07001711 Mutex::Autolock lock(mLock);
Andy Hung179652e2015-05-31 22:49:46 -07001712 mCallback = cb;
1713 mCallbackCookie = cookie;
1714
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001715 // Check whether we can recycle the track
1716 bool reuse = false;
1717 bool bothOffloaded = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001718
Glenn Kasten2799d742013-05-30 14:33:29 -07001719 if (mRecycledTrack != 0) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001720 // check whether we are switching between two offloaded tracks
1721 bothOffloaded = (flags & mRecycledTrack->getFlags()
1722 & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0;
Marco Nelissen67295b52012-06-11 14:52:53 -07001723
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001724 // check if the existing track can be reused as-is, or if a new track needs to be created.
1725 reuse = true;
1726
Marco Nelissen67295b52012-06-11 14:52:53 -07001727 if ((mCallbackData == NULL && mCallback != NULL) ||
1728 (mCallbackData != NULL && mCallback == NULL)) {
1729 // recycled track uses callbacks but the caller wants to use writes, or vice versa
1730 ALOGV("can't chain callback and write");
1731 reuse = false;
1732 } else if ((mRecycledTrack->getSampleRate() != sampleRate) ||
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001733 (mRecycledTrack->channelCount() != (uint32_t)channelCount) ) {
1734 ALOGV("samplerate, channelcount differ: %u/%u Hz, %u/%d ch",
Marco Nelissen67295b52012-06-11 14:52:53 -07001735 mRecycledTrack->getSampleRate(), sampleRate,
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001736 mRecycledTrack->channelCount(), channelCount);
Marco Nelissen67295b52012-06-11 14:52:53 -07001737 reuse = false;
1738 } else if (flags != mFlags) {
1739 ALOGV("output flags differ %08x/%08x", flags, mFlags);
1740 reuse = false;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001741 } else if (mRecycledTrack->format() != format) {
1742 reuse = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001743 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001744 } else {
1745 ALOGV("no track available to recycle");
1746 }
1747
1748 ALOGV_IF(bothOffloaded, "both tracks offloaded");
1749
1750 // If we can't recycle and both tracks are offloaded
1751 // we must close the previous output before opening a new one
1752 if (bothOffloaded && !reuse) {
1753 ALOGV("both offloaded and not recycling");
Andy Hungd1c74342015-07-07 16:54:23 -07001754 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001755 }
1756
1757 sp<AudioTrack> t;
1758 CallbackData *newcbd = NULL;
1759
1760 // We don't attempt to create a new track if we are recycling an
1761 // offloaded track. But, if we are recycling a non-offloaded or we
1762 // are switching where one is offloaded and one isn't then we create
1763 // the new track in advance so that we can read additional stream info
1764
1765 if (!(reuse && bothOffloaded)) {
1766 ALOGV("creating new AudioTrack");
1767
1768 if (mCallback != NULL) {
1769 newcbd = new CallbackData(this);
1770 t = new AudioTrack(
1771 mStreamType,
1772 sampleRate,
1773 format,
1774 channelMask,
1775 frameCount,
1776 flags,
1777 CallbackWrapper,
1778 newcbd,
1779 0, // notification frames
1780 mSessionId,
1781 AudioTrack::TRANSFER_CALLBACK,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001782 offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -08001783 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001784 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001785 mAttributes,
1786 doNotReconnect);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001787 } else {
Andy Hungff874dc2016-04-11 16:49:09 -07001788 // TODO: Due to buffer memory concerns, we use a max target playback speed
1789 // based on mPlaybackRate at the time of open (instead of kMaxRequiredSpeed),
1790 // also clamping the target speed to 1.0 <= targetSpeed <= kMaxRequiredSpeed.
1791 const float targetSpeed =
1792 std::min(std::max(mPlaybackRate.mSpeed, 1.0f), kMaxRequiredSpeed);
1793 ALOGW_IF(targetSpeed != mPlaybackRate.mSpeed,
1794 "track target speed:%f clamped from playback speed:%f",
1795 targetSpeed, mPlaybackRate.mSpeed);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001796 t = new AudioTrack(
1797 mStreamType,
1798 sampleRate,
1799 format,
1800 channelMask,
1801 frameCount,
1802 flags,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001803 NULL, // callback
1804 NULL, // user data
1805 0, // notification frames
1806 mSessionId,
1807 AudioTrack::TRANSFER_DEFAULT,
1808 NULL, // offload info
Marco Nelissend457c972014-02-11 08:47:07 -08001809 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001810 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001811 mAttributes,
Andy Hungff874dc2016-04-11 16:49:09 -07001812 doNotReconnect,
1813 targetSpeed);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001814 }
1815
1816 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1817 ALOGE("Unable to create audio track");
1818 delete newcbd;
Glenn Kasten3e98ecd2015-05-18 13:13:24 -07001819 // t goes out of scope, so reference count drops to zero
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001820 return NO_INIT;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001821 } else {
1822 // successful AudioTrack initialization implies a legacy stream type was generated
1823 // from the audio attributes
1824 mStreamType = t->streamType();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001825 }
1826 }
1827
1828 if (reuse) {
1829 CHECK(mRecycledTrack != NULL);
1830
1831 if (!bothOffloaded) {
1832 if (mRecycledTrack->frameCount() != t->frameCount()) {
Andy Hung833b4752016-04-04 17:15:48 -07001833 ALOGV("framecount differs: %zu/%zu frames",
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001834 mRecycledTrack->frameCount(), t->frameCount());
1835 reuse = false;
1836 }
1837 }
1838
Marco Nelissen67295b52012-06-11 14:52:53 -07001839 if (reuse) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001840 ALOGV("chaining to next output and recycling track");
Andy Hungd1c74342015-07-07 16:54:23 -07001841 close_l();
Marco Nelissen67295b52012-06-11 14:52:53 -07001842 mTrack = mRecycledTrack;
Glenn Kasten2799d742013-05-30 14:33:29 -07001843 mRecycledTrack.clear();
Marco Nelissen67295b52012-06-11 14:52:53 -07001844 if (mCallbackData != NULL) {
1845 mCallbackData->setOutput(this);
1846 }
Marco Nelissen67295b52012-06-11 14:52:53 -07001847 delete newcbd;
Wei Jiae0bbac92016-07-18 16:04:53 -07001848 return updateTrack();
Marco Nelissen67295b52012-06-11 14:52:53 -07001849 }
Marco Nelissen67295b52012-06-11 14:52:53 -07001850 }
1851
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001852 // we're not going to reuse the track, unblock and flush it
1853 // this was done earlier if both tracks are offloaded
1854 if (!bothOffloaded) {
Andy Hungd1c74342015-07-07 16:54:23 -07001855 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001856 }
1857
1858 CHECK((t != NULL) && ((mCallback == NULL) || (newcbd != NULL)));
1859
Marco Nelissen67295b52012-06-11 14:52:53 -07001860 mCallbackData = newcbd;
Steve Block3856b092011-10-20 11:56:00 +01001861 ALOGV("setVolume");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001862 t->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07001863
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001864 mSampleRateHz = sampleRate;
Preetam Singh Ranawat2e17eef2015-08-12 12:11:46 -07001865 mFlags = flags;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001866 mMsecsPerFrame = 1E3f / (mPlaybackRate.mSpeed * sampleRate);
Andy Hungd1c74342015-07-07 16:54:23 -07001867 mFrameSize = t->frameSize();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001868 mTrack = t;
Eric Laurent2beeb502010-07-16 07:43:46 -07001869
Wei Jiae0bbac92016-07-18 16:04:53 -07001870 return updateTrack();
1871}
1872
1873status_t MediaPlayerService::AudioOutput::updateTrack() {
1874 if (mTrack == NULL) {
1875 return NO_ERROR;
1876 }
1877
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001878 status_t res = NO_ERROR;
Wei Jia0162d002015-06-09 11:59:33 -07001879 // Note some output devices may give us a direct track even though we don't specify it.
1880 // Example: Line application b/17459982.
Wei Jiae0bbac92016-07-18 16:04:53 -07001881 if ((mTrack->getFlags()
1882 & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) {
1883 res = mTrack->setPlaybackRate(mPlaybackRate);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001884 if (res == NO_ERROR) {
Wei Jiae0bbac92016-07-18 16:04:53 -07001885 mTrack->setAuxEffectSendLevel(mSendLevel);
1886 res = mTrack->attachAuxEffect(mAuxEffectId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001887 }
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001888 }
Wei Jiae0bbac92016-07-18 16:04:53 -07001889 ALOGV("updateTrack() DONE status %d", res);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001890 return res;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001891}
1892
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001893status_t MediaPlayerService::AudioOutput::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001894{
Steve Block3856b092011-10-20 11:56:00 +01001895 ALOGV("start");
Andy Hungd1c74342015-07-07 16:54:23 -07001896 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001897 if (mCallbackData != NULL) {
1898 mCallbackData->endTrackSwitch();
1899 }
Glenn Kasten2799d742013-05-30 14:33:29 -07001900 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001901 mTrack->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07001902 mTrack->setAuxEffectSendLevel(mSendLevel);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001903 return mTrack->start();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001904 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001905 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001906}
1907
Marco Nelissen6b74d672012-02-28 16:07:44 -08001908void MediaPlayerService::AudioOutput::setNextOutput(const sp<AudioOutput>& nextOutput) {
Andy Hungd1c74342015-07-07 16:54:23 -07001909 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001910 mNextOutput = nextOutput;
1911}
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08001912
Marco Nelissen6b74d672012-02-28 16:07:44 -08001913void MediaPlayerService::AudioOutput::switchToNextOutput() {
1914 ALOGV("switchToNextOutput");
Andy Hungd1c74342015-07-07 16:54:23 -07001915
1916 // Try to acquire the callback lock before moving track (without incurring deadlock).
1917 const unsigned kMaxSwitchTries = 100;
1918 Mutex::Autolock lock(mLock);
1919 for (unsigned tries = 0;;) {
1920 if (mTrack == 0) {
1921 return;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001922 }
Andy Hungd1c74342015-07-07 16:54:23 -07001923 if (mNextOutput != NULL && mNextOutput != this) {
1924 if (mCallbackData != NULL) {
1925 // two alternative approaches
1926#if 1
1927 CallbackData *callbackData = mCallbackData;
1928 mLock.unlock();
1929 // proper acquisition sequence
1930 callbackData->lock();
1931 mLock.lock();
1932 // Caution: it is unlikely that someone deleted our callback or changed our target
1933 if (callbackData != mCallbackData || mNextOutput == NULL || mNextOutput == this) {
1934 // fatal if we are starved out.
1935 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
1936 "switchToNextOutput() cannot obtain correct lock sequence");
1937 callbackData->unlock();
1938 continue;
1939 }
1940 callbackData->mSwitching = true; // begin track switch
Wei Jiaadee56a2016-08-05 15:40:34 -07001941 callbackData->setOutput(NULL);
Andy Hungd1c74342015-07-07 16:54:23 -07001942#else
1943 // tryBeginTrackSwitch() returns false if the callback has the lock.
1944 if (!mCallbackData->tryBeginTrackSwitch()) {
1945 // fatal if we are starved out.
1946 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
1947 "switchToNextOutput() cannot obtain callback lock");
1948 mLock.unlock();
1949 usleep(5 * 1000 /* usec */); // allow callback to use AudioOutput
1950 mLock.lock();
1951 continue;
1952 }
1953#endif
1954 }
1955
1956 Mutex::Autolock nextLock(mNextOutput->mLock);
1957
1958 // If the next output track is not NULL, then it has been
1959 // opened already for playback.
1960 // This is possible even without the next player being started,
1961 // for example, the next player could be prepared and seeked.
1962 //
1963 // Presuming it isn't advisable to force the track over.
1964 if (mNextOutput->mTrack == NULL) {
1965 ALOGD("Recycling track for gapless playback");
1966 delete mNextOutput->mCallbackData;
1967 mNextOutput->mCallbackData = mCallbackData;
1968 mNextOutput->mRecycledTrack = mTrack;
1969 mNextOutput->mSampleRateHz = mSampleRateHz;
1970 mNextOutput->mMsecsPerFrame = mMsecsPerFrame;
Andy Hungd1c74342015-07-07 16:54:23 -07001971 mNextOutput->mFlags = mFlags;
1972 mNextOutput->mFrameSize = mFrameSize;
1973 close_l();
1974 mCallbackData = NULL; // destruction handled by mNextOutput
1975 } else {
1976 ALOGW("Ignoring gapless playback because next player has already started");
1977 // remove track in case resource needed for future players.
1978 if (mCallbackData != NULL) {
1979 mCallbackData->endTrackSwitch(); // release lock for callbacks before close.
1980 }
1981 close_l();
1982 }
1983 }
1984 break;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001985 }
1986}
1987
Wei Jia7d3f4df2015-03-03 15:28:00 -08001988ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001989{
Andy Hungd1c74342015-07-07 16:54:23 -07001990 Mutex::Autolock lock(mLock);
Glenn Kastenadad3d72014-02-21 14:51:43 -08001991 LOG_ALWAYS_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
Andreas Huber20111aa2009-07-14 16:56:47 -07001992
Steve Block3856b092011-10-20 11:56:00 +01001993 //ALOGV("write(%p, %u)", buffer, size);
Glenn Kasten2799d742013-05-30 14:33:29 -07001994 if (mTrack != 0) {
Andy Hung2f6e73d2016-04-08 12:12:58 -07001995 return mTrack->write(buffer, size, blocking);
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001996 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001997 return NO_INIT;
1998}
1999
2000void MediaPlayerService::AudioOutput::stop()
2001{
Steve Block3856b092011-10-20 11:56:00 +01002002 ALOGV("stop");
Andy Hungd1c74342015-07-07 16:54:23 -07002003 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002004 if (mTrack != 0) mTrack->stop();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002005}
2006
2007void MediaPlayerService::AudioOutput::flush()
2008{
Steve Block3856b092011-10-20 11:56:00 +01002009 ALOGV("flush");
Andy Hungd1c74342015-07-07 16:54:23 -07002010 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002011 if (mTrack != 0) mTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002012}
2013
2014void MediaPlayerService::AudioOutput::pause()
2015{
Steve Block3856b092011-10-20 11:56:00 +01002016 ALOGV("pause");
Andy Hungd1c74342015-07-07 16:54:23 -07002017 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002018 if (mTrack != 0) mTrack->pause();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002019}
2020
2021void MediaPlayerService::AudioOutput::close()
2022{
Steve Block3856b092011-10-20 11:56:00 +01002023 ALOGV("close");
Erik Wolsheimer7845a1f2015-10-30 12:07:52 -07002024 sp<AudioTrack> track;
2025 {
2026 Mutex::Autolock lock(mLock);
2027 track = mTrack;
2028 close_l(); // clears mTrack
2029 }
2030 // destruction of the track occurs outside of mutex.
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002031}
2032
2033void MediaPlayerService::AudioOutput::setVolume(float left, float right)
2034{
Steve Block3856b092011-10-20 11:56:00 +01002035 ALOGV("setVolume(%f, %f)", left, right);
Andy Hungd1c74342015-07-07 16:54:23 -07002036 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002037 mLeftVolume = left;
2038 mRightVolume = right;
Glenn Kasten2799d742013-05-30 14:33:29 -07002039 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002040 mTrack->setVolume(left, right);
2041 }
2042}
2043
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002044status_t MediaPlayerService::AudioOutput::setPlaybackRate(const AudioPlaybackRate &rate)
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002045{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002046 ALOGV("setPlaybackRate(%f %f %d %d)",
2047 rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Andy Hungd1c74342015-07-07 16:54:23 -07002048 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002049 if (mTrack == 0) {
2050 // remember rate so that we can set it when the track is opened
2051 mPlaybackRate = rate;
2052 return OK;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002053 }
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002054 status_t res = mTrack->setPlaybackRate(rate);
2055 if (res != NO_ERROR) {
2056 return res;
2057 }
2058 // rate.mSpeed is always greater than 0 if setPlaybackRate succeeded
2059 CHECK_GT(rate.mSpeed, 0.f);
2060 mPlaybackRate = rate;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002061 if (mSampleRateHz != 0) {
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002062 mMsecsPerFrame = 1E3f / (rate.mSpeed * mSampleRateHz);
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002063 }
2064 return res;
2065}
2066
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002067status_t MediaPlayerService::AudioOutput::getPlaybackRate(AudioPlaybackRate *rate)
2068{
2069 ALOGV("setPlaybackRate");
Andy Hungd1c74342015-07-07 16:54:23 -07002070 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002071 if (mTrack == 0) {
2072 return NO_INIT;
2073 }
2074 *rate = mTrack->getPlaybackRate();
2075 return NO_ERROR;
2076}
2077
Eric Laurent2beeb502010-07-16 07:43:46 -07002078status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
2079{
Steve Block3856b092011-10-20 11:56:00 +01002080 ALOGV("setAuxEffectSendLevel(%f)", level);
Andy Hungd1c74342015-07-07 16:54:23 -07002081 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002082 mSendLevel = level;
Glenn Kasten2799d742013-05-30 14:33:29 -07002083 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002084 return mTrack->setAuxEffectSendLevel(level);
2085 }
2086 return NO_ERROR;
2087}
2088
2089status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
2090{
Steve Block3856b092011-10-20 11:56:00 +01002091 ALOGV("attachAuxEffect(%d)", effectId);
Andy Hungd1c74342015-07-07 16:54:23 -07002092 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002093 mAuxEffectId = effectId;
Glenn Kasten2799d742013-05-30 14:33:29 -07002094 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002095 return mTrack->attachAuxEffect(effectId);
2096 }
2097 return NO_ERROR;
2098}
2099
Andreas Huber20111aa2009-07-14 16:56:47 -07002100// static
2101void MediaPlayerService::AudioOutput::CallbackWrapper(
Glenn Kastend217a8c2011-06-01 15:20:35 -07002102 int event, void *cookie, void *info) {
Steve Block3856b092011-10-20 11:56:00 +01002103 //ALOGV("callbackwrapper");
Marco Nelissen6b74d672012-02-28 16:07:44 -08002104 CallbackData *data = (CallbackData*)cookie;
Andy Hungd1c74342015-07-07 16:54:23 -07002105 // lock to ensure we aren't caught in the middle of a track switch.
Marco Nelissen6b74d672012-02-28 16:07:44 -08002106 data->lock();
2107 AudioOutput *me = data->getOutput();
Andreas Huber20111aa2009-07-14 16:56:47 -07002108 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002109 if (me == NULL) {
2110 // no output set, likely because the track was scheduled to be reused
2111 // by another player, but the format turned out to be incompatible.
2112 data->unlock();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002113 if (buffer != NULL) {
2114 buffer->size = 0;
2115 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08002116 return;
2117 }
Andreas Huber20111aa2009-07-14 16:56:47 -07002118
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002119 switch(event) {
2120 case AudioTrack::EVENT_MORE_DATA: {
2121 size_t actualSize = (*me->mCallback)(
2122 me, buffer->raw, buffer->size, me->mCallbackCookie,
2123 CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002124
Andy Hung719b46b2015-05-31 22:18:25 -07002125 // Log when no data is returned from the callback.
2126 // (1) We may have no data (especially with network streaming sources).
2127 // (2) We may have reached the EOS and the audio track is not stopped yet.
2128 // Note that AwesomePlayer/AudioPlayer will only return zero size when it reaches the EOS.
2129 // NuPlayerRenderer will return zero when it doesn't have data (it doesn't block to fill).
2130 //
2131 // This is a benign busy-wait, with the next data request generated 10 ms or more later;
2132 // nevertheless for power reasons, we don't want to see too many of these.
Andreas Huber2e8ffaf2010-02-18 16:45:13 -08002133
Andy Hung719b46b2015-05-31 22:18:25 -07002134 ALOGV_IF(actualSize == 0 && buffer->size > 0, "callbackwrapper: empty buffer returned");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002135
2136 buffer->size = actualSize;
2137 } break;
2138
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002139 case AudioTrack::EVENT_STREAM_END:
Andy Hung719b46b2015-05-31 22:18:25 -07002140 // currently only occurs for offloaded callbacks
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002141 ALOGV("callbackwrapper: deliver EVENT_STREAM_END");
2142 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2143 me->mCallbackCookie, CB_EVENT_STREAM_END);
2144 break;
2145
2146 case AudioTrack::EVENT_NEW_IAUDIOTRACK :
2147 ALOGV("callbackwrapper: deliver EVENT_TEAR_DOWN");
2148 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2149 me->mCallbackCookie, CB_EVENT_TEAR_DOWN);
2150 break;
2151
Glenn Kasten421743b2015-06-01 08:18:08 -07002152 case AudioTrack::EVENT_UNDERRUN:
Andy Hung719b46b2015-05-31 22:18:25 -07002153 // This occurs when there is no data available, typically
Glenn Kasten421743b2015-06-01 08:18:08 -07002154 // when there is a failure to supply data to the AudioTrack. It can also
2155 // occur in non-offloaded mode when the audio device comes out of standby.
2156 //
Andy Hung719b46b2015-05-31 22:18:25 -07002157 // If an AudioTrack underruns it outputs silence. Since this happens suddenly
2158 // it may sound like an audible pop or glitch.
2159 //
2160 // The underrun event is sent once per track underrun; the condition is reset
2161 // when more data is sent to the AudioTrack.
Eric Laurente93cc032016-05-05 10:15:10 -07002162 ALOGD("callbackwrapper: EVENT_UNDERRUN (discarded)");
Glenn Kasten421743b2015-06-01 08:18:08 -07002163 break;
2164
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002165 default:
2166 ALOGE("received unknown event type: %d inside CallbackWrapper !", event);
Andreas Huber51c1e0e2011-04-04 11:43:40 -07002167 }
2168
Marco Nelissen6b74d672012-02-28 16:07:44 -08002169 data->unlock();
Andreas Huber20111aa2009-07-14 16:56:47 -07002170}
2171
Glenn Kastend848eb42016-03-08 13:42:11 -08002172audio_session_t MediaPlayerService::AudioOutput::getSessionId() const
Eric Laurent8c563ed2010-10-07 18:23:03 -07002173{
Andy Hungd1c74342015-07-07 16:54:23 -07002174 Mutex::Autolock lock(mLock);
Eric Laurent8c563ed2010-10-07 18:23:03 -07002175 return mSessionId;
2176}
2177
Eric Laurent6f59db12013-07-26 17:16:50 -07002178uint32_t MediaPlayerService::AudioOutput::getSampleRate() const
2179{
Andy Hungd1c74342015-07-07 16:54:23 -07002180 Mutex::Autolock lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -07002181 if (mTrack == 0) return 0;
2182 return mTrack->getSampleRate();
2183}
2184
Andy Hungf2c87b32016-04-07 19:49:29 -07002185int64_t MediaPlayerService::AudioOutput::getBufferDurationInUs() const
2186{
2187 Mutex::Autolock lock(mLock);
2188 if (mTrack == 0) {
2189 return 0;
2190 }
2191 int64_t duration;
2192 if (mTrack->getBufferDurationInUs(&duration) != OK) {
2193 return 0;
2194 }
2195 return duration;
2196}
2197
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002198////////////////////////////////////////////////////////////////////////////////
2199
2200struct CallbackThread : public Thread {
2201 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
2202 MediaPlayerBase::AudioSink::AudioCallback cb,
2203 void *cookie);
2204
2205protected:
2206 virtual ~CallbackThread();
2207
2208 virtual bool threadLoop();
2209
2210private:
2211 wp<MediaPlayerBase::AudioSink> mSink;
2212 MediaPlayerBase::AudioSink::AudioCallback mCallback;
2213 void *mCookie;
2214 void *mBuffer;
2215 size_t mBufferSize;
2216
2217 CallbackThread(const CallbackThread &);
2218 CallbackThread &operator=(const CallbackThread &);
2219};
2220
2221CallbackThread::CallbackThread(
2222 const wp<MediaPlayerBase::AudioSink> &sink,
2223 MediaPlayerBase::AudioSink::AudioCallback cb,
2224 void *cookie)
2225 : mSink(sink),
2226 mCallback(cb),
2227 mCookie(cookie),
2228 mBuffer(NULL),
2229 mBufferSize(0) {
2230}
2231
2232CallbackThread::~CallbackThread() {
2233 if (mBuffer) {
2234 free(mBuffer);
2235 mBuffer = NULL;
2236 }
2237}
2238
2239bool CallbackThread::threadLoop() {
2240 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
2241 if (sink == NULL) {
2242 return false;
2243 }
2244
2245 if (mBuffer == NULL) {
2246 mBufferSize = sink->bufferSize();
2247 mBuffer = malloc(mBufferSize);
2248 }
2249
2250 size_t actualSize =
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002251 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie,
2252 MediaPlayerBase::AudioSink::CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002253
2254 if (actualSize > 0) {
2255 sink->write(mBuffer, actualSize);
Andy Hunga31335a2014-08-20 17:37:59 -07002256 // Could return false on sink->write() error or short count.
2257 // Not necessarily appropriate but would work for AudioCache behavior.
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002258 }
2259
2260 return true;
2261}
2262
2263////////////////////////////////////////////////////////////////////////////////
2264
Gloria Wang7cf180c2011-02-19 18:37:57 -08002265void MediaPlayerService::addBatteryData(uint32_t params)
2266{
2267 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002268
2269 int32_t time = systemTime() / 1000000L;
2270
2271 // change audio output devices. This notification comes from AudioFlinger
2272 if ((params & kBatteryDataSpeakerOn)
2273 || (params & kBatteryDataOtherAudioDeviceOn)) {
2274
2275 int deviceOn[NUM_AUDIO_DEVICES];
2276 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2277 deviceOn[i] = 0;
2278 }
2279
2280 if ((params & kBatteryDataSpeakerOn)
2281 && (params & kBatteryDataOtherAudioDeviceOn)) {
2282 deviceOn[SPEAKER_AND_OTHER] = 1;
2283 } else if (params & kBatteryDataSpeakerOn) {
2284 deviceOn[SPEAKER] = 1;
2285 } else {
2286 deviceOn[OTHER_AUDIO_DEVICE] = 1;
2287 }
2288
2289 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2290 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
2291
2292 if (mBatteryAudio.refCount > 0) { // if playing audio
2293 if (!deviceOn[i]) {
2294 mBatteryAudio.lastTime[i] += time;
2295 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2296 mBatteryAudio.lastTime[i] = 0;
2297 } else {
2298 mBatteryAudio.lastTime[i] = 0 - time;
2299 }
2300 }
2301
2302 mBatteryAudio.deviceOn[i] = deviceOn[i];
2303 }
2304 }
2305 return;
2306 }
2307
Marco Nelissenb7848f12014-12-04 08:57:56 -08002308 // an audio stream is started
Gloria Wang9ee159b2011-02-24 14:51:45 -08002309 if (params & kBatteryDataAudioFlingerStart) {
2310 // record the start time only if currently no other audio
2311 // is being played
2312 if (mBatteryAudio.refCount == 0) {
2313 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2314 if (mBatteryAudio.deviceOn[i]) {
2315 mBatteryAudio.lastTime[i] -= time;
2316 }
2317 }
2318 }
2319
2320 mBatteryAudio.refCount ++;
2321 return;
2322
2323 } else if (params & kBatteryDataAudioFlingerStop) {
2324 if (mBatteryAudio.refCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002325 ALOGW("Battery track warning: refCount is <= 0");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002326 return;
2327 }
2328
2329 // record the stop time only if currently this is the only
2330 // audio being played
2331 if (mBatteryAudio.refCount == 1) {
2332 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2333 if (mBatteryAudio.deviceOn[i]) {
2334 mBatteryAudio.lastTime[i] += time;
2335 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2336 mBatteryAudio.lastTime[i] = 0;
2337 }
2338 }
2339 }
2340
2341 mBatteryAudio.refCount --;
2342 return;
2343 }
2344
Gloria Wang7cf180c2011-02-19 18:37:57 -08002345 int uid = IPCThreadState::self()->getCallingUid();
2346 if (uid == AID_MEDIA) {
2347 return;
2348 }
2349 int index = mBatteryData.indexOfKey(uid);
Gloria Wang7cf180c2011-02-19 18:37:57 -08002350
2351 if (index < 0) { // create a new entry for this UID
2352 BatteryUsageInfo info;
2353 info.audioTotalTime = 0;
2354 info.videoTotalTime = 0;
2355 info.audioLastTime = 0;
2356 info.videoLastTime = 0;
2357 info.refCount = 0;
2358
Gloria Wang9ee159b2011-02-24 14:51:45 -08002359 if (mBatteryData.add(uid, info) == NO_MEMORY) {
Steve Block29357bc2012-01-06 19:20:56 +00002360 ALOGE("Battery track error: no memory for new app");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002361 return;
2362 }
Gloria Wang7cf180c2011-02-19 18:37:57 -08002363 }
2364
2365 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
2366
2367 if (params & kBatteryDataCodecStarted) {
2368 if (params & kBatteryDataTrackAudio) {
2369 info.audioLastTime -= time;
2370 info.refCount ++;
2371 }
2372 if (params & kBatteryDataTrackVideo) {
2373 info.videoLastTime -= time;
2374 info.refCount ++;
2375 }
2376 } else {
2377 if (info.refCount == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002378 ALOGW("Battery track warning: refCount is already 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002379 return;
2380 } else if (info.refCount < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00002381 ALOGE("Battery track error: refCount < 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002382 mBatteryData.removeItem(uid);
2383 return;
2384 }
2385
2386 if (params & kBatteryDataTrackAudio) {
2387 info.audioLastTime += time;
2388 info.refCount --;
2389 }
2390 if (params & kBatteryDataTrackVideo) {
2391 info.videoLastTime += time;
2392 info.refCount --;
2393 }
2394
2395 // no stream is being played by this UID
2396 if (info.refCount == 0) {
2397 info.audioTotalTime += info.audioLastTime;
2398 info.audioLastTime = 0;
2399 info.videoTotalTime += info.videoLastTime;
2400 info.videoLastTime = 0;
2401 }
2402 }
2403}
2404
2405status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
2406 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002407
2408 // audio output devices usage
2409 int32_t time = systemTime() / 1000000L; //in ms
2410 int32_t totalTime;
2411
2412 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2413 totalTime = mBatteryAudio.totalTime[i];
2414
2415 if (mBatteryAudio.deviceOn[i]
2416 && (mBatteryAudio.lastTime[i] != 0)) {
2417 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
2418 totalTime += tmpTime;
2419 }
2420
2421 reply->writeInt32(totalTime);
2422 // reset the total time
2423 mBatteryAudio.totalTime[i] = 0;
2424 }
2425
2426 // codec usage
Gloria Wang7cf180c2011-02-19 18:37:57 -08002427 BatteryUsageInfo info;
2428 int size = mBatteryData.size();
2429
2430 reply->writeInt32(size);
2431 int i = 0;
2432
2433 while (i < size) {
2434 info = mBatteryData.valueAt(i);
2435
2436 reply->writeInt32(mBatteryData.keyAt(i)); //UID
2437 reply->writeInt32(info.audioTotalTime);
2438 reply->writeInt32(info.videoTotalTime);
2439
2440 info.audioTotalTime = 0;
2441 info.videoTotalTime = 0;
2442
2443 // remove the UID entry where no stream is being played
2444 if (info.refCount <= 0) {
2445 mBatteryData.removeItemsAt(i);
2446 size --;
2447 i --;
2448 }
2449 i++;
2450 }
2451 return NO_ERROR;
2452}
nikoa64c8c72009-07-20 15:07:26 -07002453} // namespace android