blob: da95817512e4de8d970aaf59d74f341aefa85195 [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
Andreas Huber1b86fe02014-01-29 11:13:26 -080048#include <media/IMediaHTTPService.h>
Jeff Brown2013a542012-09-04 21:38:42 -070049#include <media/IRemoteDisplay.h>
50#include <media/IRemoteDisplayClient.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080051#include <media/MediaPlayerInterface.h>
52#include <media/mediarecorder.h>
53#include <media/MediaMetadataRetrieverInterface.h>
nikoa64c8c72009-07-20 15:07:26 -070054#include <media/Metadata.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080055#include <media/AudioTrack.h>
James Dong8635b7b2011-03-14 17:01:38 -070056#include <media/MemoryLeakTrackUtil.h>
Dongwon Kangd91dc5a2017-10-10 00:07:09 -070057#include <media/stagefright/InterfaceUtils.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>
Chong Zhang181fd9b2017-02-16 15:53:03 -080063#include <media/stagefright/SurfaceUtils.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070064#include <mediautils/BatteryNotifier.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080065
Andy Hung53541292016-04-13 16:48:51 -070066#include <memunreachable/memunreachable.h>
Dima Zavin64760242011-05-11 14:15:23 -070067#include <system/audio.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070068
Gloria Wang7cf180c2011-02-19 18:37:57 -080069#include <private/android_filesystem_config.h>
70
James Dong559bf282012-03-28 10:29:14 -070071#include "ActivityManager.h"
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080072#include "MediaRecorderClient.h"
73#include "MediaPlayerService.h"
74#include "MetadataRetrieverClient.h"
John Grossman44a7e422012-06-21 17:29:24 -070075#include "MediaPlayerFactory.h"
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080076
Nicolas Catania14d27472009-07-13 14:37:49 -070077#include "TestPlayerStub.h"
Andreas Huberf9334412010-12-15 15:17:42 -080078#include "nuplayer/NuPlayerDriver.h"
Andreas Huber20111aa2009-07-14 16:56:47 -070079
Andreas Huberb7319a72013-05-29 14:20:52 -070080#include "HTTPBase.h"
Andreas Hubered3e3e02012-03-26 11:13:27 -070081
Wei Jia502c2f42017-07-13 17:47:56 -070082static const int kDumpLockRetries = 50;
83static const int kDumpLockSleepUs = 20000;
84
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;
Ivan Lozano8cf3a072017-08-09 09:01:33 -070092using android::media::VolumeShaper;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070093
94// Max number of entries in the filter.
95const int kMaxFilterSize = 64; // I pulled that out of thin air.
96
Andy Hungff874dc2016-04-11 16:49:09 -070097const float kMaxRequiredSpeed = 8.0f; // for PCM tracks allow up to 8x speedup.
98
nikoa64c8c72009-07-20 15:07:26 -070099// FIXME: Move all the metadata related function in the Metadata.cpp
nikod608a812009-07-16 16:39:53 -0700100
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700101
102// Unmarshall a filter from a Parcel.
103// Filter format in a parcel:
104//
105// 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
106// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
107// | number of entries (n) |
108// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
109// | metadata type 1 |
110// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
111// | metadata type 2 |
112// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
113// ....
114// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
115// | metadata type n |
116// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
117//
118// @param p Parcel that should start with a filter.
119// @param[out] filter On exit contains the list of metadata type to be
120// filtered.
121// @param[out] status On exit contains the status code to be returned.
122// @return true if the parcel starts with a valid filter.
123bool unmarshallFilter(const Parcel& p,
nikoa64c8c72009-07-20 15:07:26 -0700124 Metadata::Filter *filter,
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700125 status_t *status)
126{
Nicolas Catania48290382009-07-10 13:53:06 -0700127 int32_t val;
128 if (p.readInt32(&val) != OK)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700129 {
Steve Block29357bc2012-01-06 19:20:56 +0000130 ALOGE("Failed to read filter's length");
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700131 *status = NOT_ENOUGH_DATA;
132 return false;
133 }
134
Nicolas Catania48290382009-07-10 13:53:06 -0700135 if( val > kMaxFilterSize || val < 0)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700136 {
Steve Block29357bc2012-01-06 19:20:56 +0000137 ALOGE("Invalid filter len %d", val);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700138 *status = BAD_VALUE;
139 return false;
140 }
141
Nicolas Catania48290382009-07-10 13:53:06 -0700142 const size_t num = val;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700143
144 filter->clear();
Nicolas Catania48290382009-07-10 13:53:06 -0700145 filter->setCapacity(num);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700146
nikoa64c8c72009-07-20 15:07:26 -0700147 size_t size = num * sizeof(Metadata::Type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700148
Nicolas Catania48290382009-07-10 13:53:06 -0700149
150 if (p.dataAvail() < size)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700151 {
Andy Hung833b4752016-04-04 17:15:48 -0700152 ALOGE("Filter too short expected %zu but got %zu", size, p.dataAvail());
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700153 *status = NOT_ENOUGH_DATA;
154 return false;
155 }
156
nikoa64c8c72009-07-20 15:07:26 -0700157 const Metadata::Type *data =
158 static_cast<const Metadata::Type*>(p.readInplace(size));
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700159
Nicolas Catania48290382009-07-10 13:53:06 -0700160 if (NULL == data)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700161 {
Steve Block29357bc2012-01-06 19:20:56 +0000162 ALOGE("Filter had no data");
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700163 *status = BAD_VALUE;
164 return false;
165 }
166
167 // TODO: The stl impl of vector would be more efficient here
168 // because it degenerates into a memcpy on pod types. Try to
169 // replace later or use stl::set.
Nicolas Catania48290382009-07-10 13:53:06 -0700170 for (size_t i = 0; i < num; ++i)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700171 {
Nicolas Catania48290382009-07-10 13:53:06 -0700172 filter->add(*data);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700173 ++data;
174 }
175 *status = OK;
176 return true;
177}
178
Nicolas Catania48290382009-07-10 13:53:06 -0700179// @param filter Of metadata type.
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700180// @param val To be searched.
181// @return true if a match was found.
nikoa64c8c72009-07-20 15:07:26 -0700182bool findMetadata(const Metadata::Filter& filter, const int32_t val)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700183{
184 // Deal with empty and ANY right away
185 if (filter.isEmpty()) return false;
nikoa64c8c72009-07-20 15:07:26 -0700186 if (filter[0] == Metadata::kAny) return true;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700187
Nicolas Catania48290382009-07-10 13:53:06 -0700188 return filter.indexOf(val) >= 0;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700189}
190
191} // anonymous namespace
192
193
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700194namespace {
195using android::Parcel;
196using android::String16;
197
198// marshalling tag indicating flattened utf16 tags
199// keep in sync with frameworks/base/media/java/android/media/AudioAttributes.java
200const int32_t kAudioAttributesMarshallTagFlattenTags = 1;
201
202// Audio attributes format in a parcel:
203//
204// 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
205// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
206// | usage |
207// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
208// | content_type |
209// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Hyejin Kim4f418f92014-09-05 15:50:03 +0900210// | source |
211// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700212// | flags |
213// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
214// | kAudioAttributesMarshallTagFlattenTags | // ignore tags if not found
215// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
216// | flattened tags in UTF16 |
217// | ... |
218// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
219//
220// @param p Parcel that contains audio attributes.
221// @param[out] attributes On exit points to an initialized audio_attributes_t structure
222// @param[out] status On exit contains the status code to be returned.
223void unmarshallAudioAttributes(const Parcel& parcel, audio_attributes_t *attributes)
224{
225 attributes->usage = (audio_usage_t) parcel.readInt32();
226 attributes->content_type = (audio_content_type_t) parcel.readInt32();
Hyejin Kim4f418f92014-09-05 15:50:03 +0900227 attributes->source = (audio_source_t) parcel.readInt32();
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700228 attributes->flags = (audio_flags_mask_t) parcel.readInt32();
229 const bool hasFlattenedTag = (parcel.readInt32() == kAudioAttributesMarshallTagFlattenTags);
230 if (hasFlattenedTag) {
231 // the tags are UTF16, convert to UTF8
232 String16 tags = parcel.readString16();
233 ssize_t realTagSize = utf16_to_utf8_length(tags.string(), tags.size());
234 if (realTagSize <= 0) {
235 strcpy(attributes->tags, "");
236 } else {
237 // copy the flattened string into the attributes as the destination for the conversion:
238 // copying array size -1, array for tags was calloc'd, no need to NULL-terminate it
239 size_t tagSize = realTagSize > AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 ?
240 AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 : realTagSize;
Sergio Giro1d3f4272016-06-28 18:24:52 +0100241 utf16_to_utf8(tags.string(), tagSize, attributes->tags,
242 sizeof(attributes->tags) / sizeof(attributes->tags[0]));
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700243 }
244 } else {
245 ALOGE("unmarshallAudioAttributes() received unflattened tags, ignoring tag values");
246 strcpy(attributes->tags, "");
247 }
248}
249} // anonymous namespace
250
251
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800252namespace android {
253
Marco Nelissenf09611f2015-02-13 14:12:42 -0800254extern ALooperRoster gLooperRoster;
255
256
Dave Burked681bbb2011-08-30 14:39:17 +0100257static bool checkPermission(const char* permissionString) {
Dave Burked681bbb2011-08-30 14:39:17 +0100258 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
259 bool ok = checkCallingPermission(String16(permissionString));
Steve Block29357bc2012-01-06 19:20:56 +0000260 if (!ok) ALOGE("Request requires %s", permissionString);
Dave Burked681bbb2011-08-30 14:39:17 +0100261 return ok;
262}
263
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800264// TODO: Find real cause of Audio/Video delay in PV framework and remove this workaround
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800265/* static */ int MediaPlayerService::AudioOutput::mMinBufferCount = 4;
266/* static */ bool MediaPlayerService::AudioOutput::mIsOnEmulator = false;
267
268void MediaPlayerService::instantiate() {
269 defaultServiceManager()->addService(
270 String16("media.player"), new MediaPlayerService());
271}
272
273MediaPlayerService::MediaPlayerService()
274{
Steve Block3856b092011-10-20 11:56:00 +0100275 ALOGV("MediaPlayerService created");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800276 mNextConnId = 1;
Gloria Wang9ee159b2011-02-24 14:51:45 -0800277
John Grossman44a7e422012-06-21 17:29:24 -0700278 MediaPlayerFactory::registerBuiltinFactories();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800279}
280
281MediaPlayerService::~MediaPlayerService()
282{
Steve Block3856b092011-10-20 11:56:00 +0100283 ALOGV("MediaPlayerService destroyed");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800284}
285
Svet Ganovbe71aa22015-04-28 12:06:02 -0700286sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(const String16 &opPackageName)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800287{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800288 pid_t pid = IPCThreadState::self()->getCallingPid();
Svet Ganovbe71aa22015-04-28 12:06:02 -0700289 sp<MediaRecorderClient> recorder = new MediaRecorderClient(this, pid, opPackageName);
Gloria Wangdac6a312009-10-29 15:46:37 -0700290 wp<MediaRecorderClient> w = recorder;
291 Mutex::Autolock lock(mLock);
292 mMediaRecorderClients.add(w);
Steve Block3856b092011-10-20 11:56:00 +0100293 ALOGV("Create new media recorder client from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800294 return recorder;
295}
296
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -0700297void MediaPlayerService::removeMediaRecorderClient(const wp<MediaRecorderClient>& client)
Gloria Wangdac6a312009-10-29 15:46:37 -0700298{
299 Mutex::Autolock lock(mLock);
300 mMediaRecorderClients.remove(client);
Steve Block3856b092011-10-20 11:56:00 +0100301 ALOGV("Delete media recorder client");
Gloria Wangdac6a312009-10-29 15:46:37 -0700302}
303
Glenn Kastenf37971f2012-02-03 11:06:53 -0800304sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800305{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800306 pid_t pid = IPCThreadState::self()->getCallingPid();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800307 sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
Steve Block3856b092011-10-20 11:56:00 +0100308 ALOGV("Create new media retriever from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800309 return retriever;
310}
311
Glenn Kastenf37971f2012-02-03 11:06:53 -0800312sp<IMediaPlayer> MediaPlayerService::create(const sp<IMediaPlayerClient>& client,
Glenn Kastend848eb42016-03-08 13:42:11 -0800313 audio_session_t audioSessionId)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800314{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800315 pid_t pid = IPCThreadState::self()->getCallingPid();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800316 int32_t connId = android_atomic_inc(&mNextConnId);
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700317
318 sp<Client> c = new Client(
319 this, pid, connId, client, audioSessionId,
320 IPCThreadState::self()->getCallingUid());
321
Steve Block3856b092011-10-20 11:56:00 +0100322 ALOGV("Create new client(%d) from pid %d, uid %d, ", connId, pid,
Dave Burked681bbb2011-08-30 14:39:17 +0100323 IPCThreadState::self()->getCallingUid());
324
325 wp<Client> w = c;
326 {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800327 Mutex::Autolock lock(mLock);
328 mClients.add(w);
329 }
Andreas Hubere2b10282010-11-23 11:41:34 -0800330 return c;
331}
332
Lajos Molnar1381d4b2014-08-07 15:18:35 -0700333sp<IMediaCodecList> MediaPlayerService::getCodecList() const {
334 return MediaCodecList::getLocalInstance();
335}
336
Jeff Brown2013a542012-09-04 21:38:42 -0700337sp<IRemoteDisplay> MediaPlayerService::listenForRemoteDisplay(
Chong Zhangd0a98fa2017-09-14 17:43:10 -0700338 const String16 &/*opPackageName*/,
339 const sp<IRemoteDisplayClient>& /*client*/,
340 const String8& /*iface*/) {
341 ALOGE("listenForRemoteDisplay is no longer supported!");
Jeff Brownaba33d52012-09-07 17:38:58 -0700342
Chong Zhangd0a98fa2017-09-14 17:43:10 -0700343 return NULL;
Jeff Brown2013a542012-09-04 21:38:42 -0700344}
345
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800346status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
347{
348 const size_t SIZE = 256;
349 char buffer[SIZE];
350 String8 result;
351
352 result.append(" AudioOutput\n");
353 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n",
354 mStreamType, mLeftVolume, mRightVolume);
355 result.append(buffer);
356 snprintf(buffer, 255, " msec per frame(%f), latency (%d)\n",
Eric Laurentdb354e52012-03-05 17:27:11 -0800357 mMsecsPerFrame, (mTrack != 0) ? mTrack->latency() : -1);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800358 result.append(buffer);
Eric Laurent2beeb502010-07-16 07:43:46 -0700359 snprintf(buffer, 255, " aux effect id(%d), send level (%f)\n",
360 mAuxEffectId, mSendLevel);
361 result.append(buffer);
362
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800363 ::write(fd, result.string(), result.size());
364 if (mTrack != 0) {
365 mTrack->dump(fd, args);
366 }
367 return NO_ERROR;
368}
369
Lajos Molnar6d339f12015-04-17 16:15:53 -0700370status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800371{
372 const size_t SIZE = 256;
373 char buffer[SIZE];
374 String8 result;
375 result.append(" Client\n");
376 snprintf(buffer, 255, " pid(%d), connId(%d), status(%d), looping(%s)\n",
377 mPid, mConnId, mStatus, mLoop?"true": "false");
378 result.append(buffer);
Wei Jia502c2f42017-07-13 17:47:56 -0700379
380 sp<MediaPlayerBase> p;
381 sp<AudioOutput> audioOutput;
382 bool locked = false;
383 for (int i = 0; i < kDumpLockRetries; ++i) {
384 if (mLock.tryLock() == NO_ERROR) {
385 locked = true;
386 break;
387 }
388 usleep(kDumpLockSleepUs);
Andreas Hubera0b1d4b2011-06-07 15:52:25 -0700389 }
Wei Jia502c2f42017-07-13 17:47:56 -0700390
391 if (locked) {
392 p = mPlayer;
393 audioOutput = mAudioOutput;
394 mLock.unlock();
395 } else {
396 result.append(" lock is taken, no dump from player and audio output\n");
397 }
398 write(fd, result.string(), result.size());
399
400 if (p != NULL) {
401 p->dump(fd, args);
402 }
403 if (audioOutput != 0) {
404 audioOutput->dump(fd, args);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800405 }
406 write(fd, "\n", 1);
407 return NO_ERROR;
408}
409
Marco Nelissenf09611f2015-02-13 14:12:42 -0800410/**
411 * The only arguments this understands right now are -c, -von and -voff,
412 * which are parsed by ALooperRoster::dump()
413 */
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800414status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
415{
416 const size_t SIZE = 256;
417 char buffer[SIZE];
418 String8 result;
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530419 SortedVector< sp<Client> > clients; //to serialise the mutex unlock & client destruction.
420 SortedVector< sp<MediaRecorderClient> > mediaRecorderClients;
421
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800422 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
423 snprintf(buffer, SIZE, "Permission Denial: "
424 "can't dump MediaPlayerService from pid=%d, uid=%d\n",
425 IPCThreadState::self()->getCallingPid(),
426 IPCThreadState::self()->getCallingUid());
427 result.append(buffer);
428 } else {
429 Mutex::Autolock lock(mLock);
430 for (int i = 0, n = mClients.size(); i < n; ++i) {
431 sp<Client> c = mClients[i].promote();
432 if (c != 0) c->dump(fd, args);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530433 clients.add(c);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800434 }
James Dongb9141222010-07-08 11:16:11 -0700435 if (mMediaRecorderClients.size() == 0) {
436 result.append(" No media recorder client\n\n");
437 } else {
438 for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
439 sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
James Donge579e282011-10-18 22:29:20 -0700440 if (c != 0) {
441 snprintf(buffer, 255, " MediaRecorderClient pid(%d)\n", c->mPid);
442 result.append(buffer);
443 write(fd, result.string(), result.size());
444 result = "\n";
445 c->dump(fd, args);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530446 mediaRecorderClients.add(c);
James Donge579e282011-10-18 22:29:20 -0700447 }
James Dongb9141222010-07-08 11:16:11 -0700448 }
Gloria Wangdac6a312009-10-29 15:46:37 -0700449 }
450
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800451 result.append(" Files opened and/or mapped:\n");
Marco Nelissenf09611f2015-02-13 14:12:42 -0800452 snprintf(buffer, SIZE, "/proc/%d/maps", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800453 FILE *f = fopen(buffer, "r");
454 if (f) {
455 while (!feof(f)) {
456 fgets(buffer, SIZE, f);
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700457 if (strstr(buffer, " /storage/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800458 strstr(buffer, " /system/sounds/") ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700459 strstr(buffer, " /data/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800460 strstr(buffer, " /system/media/")) {
461 result.append(" ");
462 result.append(buffer);
463 }
464 }
465 fclose(f);
466 } else {
467 result.append("couldn't open ");
468 result.append(buffer);
469 result.append("\n");
470 }
471
Marco Nelissenf09611f2015-02-13 14:12:42 -0800472 snprintf(buffer, SIZE, "/proc/%d/fd", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800473 DIR *d = opendir(buffer);
474 if (d) {
475 struct dirent *ent;
476 while((ent = readdir(d)) != NULL) {
477 if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
Marco Nelissenf09611f2015-02-13 14:12:42 -0800478 snprintf(buffer, SIZE, "/proc/%d/fd/%s", getpid(), ent->d_name);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800479 struct stat s;
480 if (lstat(buffer, &s) == 0) {
481 if ((s.st_mode & S_IFMT) == S_IFLNK) {
482 char linkto[256];
483 int len = readlink(buffer, linkto, sizeof(linkto));
484 if(len > 0) {
485 if(len > 255) {
486 linkto[252] = '.';
487 linkto[253] = '.';
488 linkto[254] = '.';
489 linkto[255] = 0;
490 } else {
491 linkto[len] = 0;
492 }
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700493 if (strstr(linkto, "/storage/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800494 strstr(linkto, "/system/sounds/") == linkto ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700495 strstr(linkto, "/data/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800496 strstr(linkto, "/system/media/") == linkto) {
497 result.append(" ");
498 result.append(buffer);
499 result.append(" -> ");
500 result.append(linkto);
501 result.append("\n");
502 }
503 }
504 } else {
505 result.append(" unexpected type for ");
506 result.append(buffer);
507 result.append("\n");
508 }
509 }
510 }
511 }
512 closedir(d);
513 } else {
514 result.append("couldn't open ");
515 result.append(buffer);
516 result.append("\n");
517 }
518
Marco Nelissenf09611f2015-02-13 14:12:42 -0800519 gLooperRoster.dump(fd, args);
520
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800521 bool dumpMem = false;
Andy Hung53541292016-04-13 16:48:51 -0700522 bool unreachableMemory = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800523 for (size_t i = 0; i < args.size(); i++) {
524 if (args[i] == String16("-m")) {
525 dumpMem = true;
Andy Hung53541292016-04-13 16:48:51 -0700526 } else if (args[i] == String16("--unreachable")) {
527 unreachableMemory = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800528 }
529 }
530 if (dumpMem) {
Andy Hung07b745e2016-05-23 16:21:07 -0700531 result.append("\nDumping memory:\n");
532 std::string s = dumpMemoryAddresses(100 /* limit */);
533 result.append(s.c_str(), s.size());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800534 }
Andy Hung53541292016-04-13 16:48:51 -0700535 if (unreachableMemory) {
536 result.append("\nDumping unreachable memory:\n");
537 // TODO - should limit be an argument parameter?
538 std::string s = GetUnreachableMemoryString(true /* contents */, 10000 /* limit */);
539 result.append(s.c_str(), s.size());
540 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800541 }
542 write(fd, result.string(), result.size());
543 return NO_ERROR;
544}
545
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -0700546void MediaPlayerService::removeClient(const wp<Client>& client)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800547{
548 Mutex::Autolock lock(mLock);
549 mClients.remove(client);
550}
551
Robert Shihee0a0e32016-08-16 16:50:54 -0700552bool MediaPlayerService::hasClient(wp<Client> client)
553{
554 Mutex::Autolock lock(mLock);
555 return mClients.indexOf(client) != NAME_NOT_FOUND;
556}
557
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700558MediaPlayerService::Client::Client(
559 const sp<MediaPlayerService>& service, pid_t pid,
560 int32_t connId, const sp<IMediaPlayerClient>& client,
Glenn Kastend848eb42016-03-08 13:42:11 -0800561 audio_session_t audioSessionId, uid_t uid)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800562{
Steve Block3856b092011-10-20 11:56:00 +0100563 ALOGV("Client(%d) constructor", connId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800564 mPid = pid;
565 mConnId = connId;
566 mService = service;
567 mClient = client;
568 mLoop = false;
569 mStatus = NO_INIT;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700570 mAudioSessionId = audioSessionId;
Andy Hung1afd0982016-11-08 16:13:44 -0800571 mUid = uid;
John Grossmanc795b642012-02-22 15:38:35 -0800572 mRetransmitEndpointValid = false;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700573 mAudioAttributes = NULL;
Pawin Vongmasa082e4f72017-12-17 02:31:18 -0800574 mListener = new Listener(this);
Eric Laurenta514bdb2010-06-21 09:27:30 -0700575
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800576#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000577 ALOGD("create Antagonizer");
Pawin Vongmasa082e4f72017-12-17 02:31:18 -0800578 mAntagonizer = new Antagonizer(mListener);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800579#endif
580}
581
582MediaPlayerService::Client::~Client()
583{
Steve Block3856b092011-10-20 11:56:00 +0100584 ALOGV("Client(%d) destructor pid = %d", mConnId, mPid);
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700585 mAudioOutput.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800586 wp<Client> client(this);
587 disconnect();
588 mService->removeClient(client);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700589 if (mAudioAttributes != NULL) {
590 free(mAudioAttributes);
591 }
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700592 clearDeathNotifiers_l();
jiabin156c6872017-10-06 09:47:15 -0700593 mAudioDeviceUpdatedListener.clear();
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();
Wei Jia502c2f42017-07-13 17:47:56 -0700606 mPlayer.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800607 }
Andreas Huber20111aa2009-07-14 16:56:47 -0700608
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800609 // clear the notification to prevent callbacks to dead client
610 // and reset the player. We assume the player will serialize
611 // access to itself if necessary.
612 if (p != 0) {
Pawin Vongmasa082e4f72017-12-17 02:31:18 -0800613 p->setNotifyCallback(0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800614#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000615 ALOGD("kill Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800616 mAntagonizer->kill();
617#endif
618 p->reset();
619 }
620
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700621 {
622 Mutex::Autolock l(mLock);
623 disconnectNativeWindow_l();
624 }
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700625
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800626 IPCThreadState::self()->flushCommands();
627}
628
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800629sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
630{
631 // determine if we have the right player type
Wei Jia502c2f42017-07-13 17:47:56 -0700632 sp<MediaPlayerBase> p = getPlayer();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800633 if ((p != NULL) && (p->playerType() != playerType)) {
Steve Block3856b092011-10-20 11:56:00 +0100634 ALOGV("delete player");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800635 p.clear();
636 }
637 if (p == NULL) {
Pawin Vongmasa082e4f72017-12-17 02:31:18 -0800638 p = MediaPlayerFactory::createPlayer(playerType, mListener, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800639 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700640
Jason Simmonsdb29e522011-08-12 13:46:55 -0700641 if (p != NULL) {
Andy Hung1afd0982016-11-08 16:13:44 -0800642 p->setUID(mUid);
Jason Simmonsdb29e522011-08-12 13:46:55 -0700643 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700644
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800645 return p;
646}
647
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700648MediaPlayerService::Client::ServiceDeathNotifier::ServiceDeathNotifier(
649 const sp<IBinder>& service,
650 const sp<MediaPlayerBase>& listener,
651 int which) {
652 mService = service;
Pawin Vongmasa9c47c972017-02-08 04:09:38 -0800653 mOmx = nullptr;
654 mListener = listener;
655 mWhich = which;
656}
657
658MediaPlayerService::Client::ServiceDeathNotifier::ServiceDeathNotifier(
659 const sp<IOmx>& omx,
660 const sp<MediaPlayerBase>& listener,
661 int which) {
662 mService = nullptr;
663 mOmx = omx;
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700664 mListener = listener;
665 mWhich = which;
666}
667
668MediaPlayerService::Client::ServiceDeathNotifier::~ServiceDeathNotifier() {
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700669}
670
671void MediaPlayerService::Client::ServiceDeathNotifier::binderDied(const wp<IBinder>& /*who*/) {
672 sp<MediaPlayerBase> listener = mListener.promote();
673 if (listener != NULL) {
674 listener->sendEvent(MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED, mWhich);
675 } else {
676 ALOGW("listener for process %d death is gone", mWhich);
677 }
678}
679
Pawin Vongmasa9c47c972017-02-08 04:09:38 -0800680void MediaPlayerService::Client::ServiceDeathNotifier::serviceDied(
681 uint64_t /* cookie */,
682 const wp<::android::hidl::base::V1_0::IBase>& /* who */) {
683 sp<MediaPlayerBase> listener = mListener.promote();
684 if (listener != NULL) {
685 listener->sendEvent(MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED, mWhich);
686 } else {
687 ALOGW("listener for process %d death is gone", mWhich);
688 }
689}
690
691void MediaPlayerService::Client::ServiceDeathNotifier::unlinkToDeath() {
692 if (mService != nullptr) {
693 mService->unlinkToDeath(this);
694 mService = nullptr;
695 } else if (mOmx != nullptr) {
696 mOmx->unlinkToDeath(this);
697 mOmx = nullptr;
698 }
699}
700
jiabin156c6872017-10-06 09:47:15 -0700701void MediaPlayerService::Client::AudioDeviceUpdatedNotifier::onAudioDeviceUpdate(
702 audio_io_handle_t audioIo,
703 audio_port_handle_t deviceId) {
704 sp<MediaPlayerBase> listener = mListener.promote();
705 if (listener != NULL) {
706 listener->sendEvent(MEDIA_AUDIO_ROUTING_CHANGED, audioIo, deviceId);
707 } else {
708 ALOGW("listener for process %d death is gone", MEDIA_AUDIO_ROUTING_CHANGED);
709 }
710}
711
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700712void MediaPlayerService::Client::clearDeathNotifiers_l() {
Pawin Vongmasa9c47c972017-02-08 04:09:38 -0800713 if (mExtractorDeathListener != nullptr) {
714 mExtractorDeathListener->unlinkToDeath();
715 mExtractorDeathListener = nullptr;
716 }
717 if (mCodecDeathListener != nullptr) {
718 mCodecDeathListener->unlinkToDeath();
719 mCodecDeathListener = nullptr;
720 }
721}
722
John Grossmanc795b642012-02-22 15:38:35 -0800723sp<MediaPlayerBase> MediaPlayerService::Client::setDataSource_pre(
724 player_type playerType)
725{
726 ALOGV("player type = %d", playerType);
727
728 // create the right type of player
729 sp<MediaPlayerBase> p = createPlayer(playerType);
730 if (p == NULL) {
731 return p;
732 }
733
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700734 sp<IServiceManager> sm = defaultServiceManager();
735 sp<IBinder> binder = sm->getService(String16("media.extractor"));
Marco Nelissen1b5a7ee2016-09-30 13:54:30 -0700736 if (binder == NULL) {
737 ALOGE("extractor service not available");
738 return NULL;
739 }
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700740 sp<ServiceDeathNotifier> extractorDeathListener =
741 new ServiceDeathNotifier(binder, p, MEDIAEXTRACTOR_PROCESS_DEATH);
742 binder->linkToDeath(extractorDeathListener);
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700743
Pawin Vongmasa620e4662017-10-27 00:12:47 -0700744 sp<IOmx> omx = IOmx::getService();
745 if (omx == nullptr) {
746 ALOGE("IOmx service is not available");
747 return NULL;
Marco Nelissen1b5a7ee2016-09-30 13:54:30 -0700748 }
Pawin Vongmasa620e4662017-10-27 00:12:47 -0700749 sp<ServiceDeathNotifier> codecDeathListener =
750 new ServiceDeathNotifier(omx, p, MEDIACODEC_PROCESS_DEATH);
751 omx->linkToDeath(codecDeathListener, 0);
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700752
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700753 Mutex::Autolock lock(mLock);
754
755 clearDeathNotifiers_l();
756 mExtractorDeathListener = extractorDeathListener;
757 mCodecDeathListener = codecDeathListener;
jiabin156c6872017-10-06 09:47:15 -0700758 mAudioDeviceUpdatedListener = new AudioDeviceUpdatedNotifier(p);
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700759
John Grossmanc795b642012-02-22 15:38:35 -0800760 if (!p->hardwareOutput()) {
Marco Nelissend457c972014-02-11 08:47:07 -0800761 mAudioOutput = new AudioOutput(mAudioSessionId, IPCThreadState::self()->getCallingUid(),
jiabin156c6872017-10-06 09:47:15 -0700762 mPid, mAudioAttributes, mAudioDeviceUpdatedListener);
John Grossmanc795b642012-02-22 15:38:35 -0800763 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
764 }
765
766 return p;
767}
768
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700769status_t MediaPlayerService::Client::setDataSource_post(
John Grossmanc795b642012-02-22 15:38:35 -0800770 const sp<MediaPlayerBase>& p,
771 status_t status)
772{
773 ALOGV(" setDataSource");
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700774 if (status != OK) {
775 ALOGE(" error: %d", status);
776 return status;
John Grossmanc795b642012-02-22 15:38:35 -0800777 }
778
779 // Set the re-transmission endpoint if one was chosen.
780 if (mRetransmitEndpointValid) {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700781 status = p->setRetransmitEndpoint(&mRetransmitEndpoint);
782 if (status != NO_ERROR) {
783 ALOGE("setRetransmitEndpoint error: %d", status);
John Grossmanc795b642012-02-22 15:38:35 -0800784 }
785 }
786
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700787 if (status == OK) {
788 Mutex::Autolock lock(mLock);
John Grossmanc795b642012-02-22 15:38:35 -0800789 mPlayer = p;
790 }
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700791 return status;
John Grossmanc795b642012-02-22 15:38:35 -0800792}
793
Andreas Huber2db84552010-01-28 11:19:57 -0800794status_t MediaPlayerService::Client::setDataSource(
Andreas Huber1b86fe02014-01-29 11:13:26 -0800795 const sp<IMediaHTTPService> &httpService,
796 const char *url,
797 const KeyedVector<String8, String8> *headers)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800798{
Steve Block3856b092011-10-20 11:56:00 +0100799 ALOGV("setDataSource(%s)", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800800 if (url == NULL)
801 return UNKNOWN_ERROR;
802
Dave Burked681bbb2011-08-30 14:39:17 +0100803 if ((strncmp(url, "http://", 7) == 0) ||
804 (strncmp(url, "https://", 8) == 0) ||
805 (strncmp(url, "rtsp://", 7) == 0)) {
806 if (!checkPermission("android.permission.INTERNET")) {
807 return PERMISSION_DENIED;
808 }
809 }
810
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800811 if (strncmp(url, "content://", 10) == 0) {
812 // get a filedescriptor for the content Uri and
813 // pass it to the setDataSource(fd) method
814
815 String16 url16(url);
816 int fd = android::openContentProviderFile(url16);
817 if (fd < 0)
818 {
Steve Block29357bc2012-01-06 19:20:56 +0000819 ALOGE("Couldn't open fd for %s", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800820 return UNKNOWN_ERROR;
821 }
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700822 status_t status = setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800823 close(fd);
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700824 return mStatus = status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800825 } else {
John Grossman44a7e422012-06-21 17:29:24 -0700826 player_type playerType = MediaPlayerFactory::getPlayerType(this, url);
John Grossmanc795b642012-02-22 15:38:35 -0800827 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
828 if (p == NULL) {
829 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800830 }
831
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700832 return mStatus =
833 setDataSource_post(
834 p, p->setDataSource(httpService, url, headers));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800835 }
836}
837
838status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
839{
Marco Nelissen83b0fd92015-09-16 13:48:07 -0700840 ALOGV("setDataSource fd=%d (%s), offset=%lld, length=%lld",
841 fd, nameForFd(fd).c_str(), (long long) offset, (long long) length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800842 struct stat sb;
843 int ret = fstat(fd, &sb);
844 if (ret != 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000845 ALOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800846 return UNKNOWN_ERROR;
847 }
848
Andy Hung833b4752016-04-04 17:15:48 -0700849 ALOGV("st_dev = %llu", static_cast<unsigned long long>(sb.st_dev));
Steve Block3856b092011-10-20 11:56:00 +0100850 ALOGV("st_mode = %u", sb.st_mode);
Mark Salyzyn77342f72014-06-18 16:31:32 -0700851 ALOGV("st_uid = %lu", static_cast<unsigned long>(sb.st_uid));
852 ALOGV("st_gid = %lu", static_cast<unsigned long>(sb.st_gid));
Andy Hung833b4752016-04-04 17:15:48 -0700853 ALOGV("st_size = %llu", static_cast<unsigned long long>(sb.st_size));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800854
855 if (offset >= sb.st_size) {
Steve Block29357bc2012-01-06 19:20:56 +0000856 ALOGE("offset error");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800857 return UNKNOWN_ERROR;
858 }
859 if (offset + length > sb.st_size) {
860 length = sb.st_size - offset;
Andy Hung833b4752016-04-04 17:15:48 -0700861 ALOGV("calculated length = %lld", (long long)length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800862 }
863
John Grossman44a7e422012-06-21 17:29:24 -0700864 player_type playerType = MediaPlayerFactory::getPlayerType(this,
865 fd,
866 offset,
867 length);
John Grossmanc795b642012-02-22 15:38:35 -0800868 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
869 if (p == NULL) {
870 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800871 }
872
873 // now set data source
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700874 return mStatus = setDataSource_post(p, p->setDataSource(fd, offset, length));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800875}
876
Andreas Hubere2b10282010-11-23 11:41:34 -0800877status_t MediaPlayerService::Client::setDataSource(
878 const sp<IStreamSource> &source) {
879 // create the right type of player
John Grossman44a7e422012-06-21 17:29:24 -0700880 player_type playerType = MediaPlayerFactory::getPlayerType(this, source);
John Grossmanc795b642012-02-22 15:38:35 -0800881 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
Andreas Hubere2b10282010-11-23 11:41:34 -0800882 if (p == NULL) {
883 return NO_INIT;
884 }
885
Andreas Hubere2b10282010-11-23 11:41:34 -0800886 // now set data source
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700887 return mStatus = setDataSource_post(p, p->setDataSource(source));
Andreas Hubere2b10282010-11-23 11:41:34 -0800888}
889
Chris Watkins99f31602015-03-20 13:06:33 -0700890status_t MediaPlayerService::Client::setDataSource(
891 const sp<IDataSource> &source) {
Dongwon Kangd91dc5a2017-10-10 00:07:09 -0700892 sp<DataSource> dataSource = CreateDataSourceFromIDataSource(source);
Chris Watkins99f31602015-03-20 13:06:33 -0700893 player_type playerType = MediaPlayerFactory::getPlayerType(this, dataSource);
894 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
895 if (p == NULL) {
896 return NO_INIT;
897 }
898 // now set data source
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700899 return mStatus = setDataSource_post(p, p->setDataSource(dataSource));
Chris Watkins99f31602015-03-20 13:06:33 -0700900}
901
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700902void MediaPlayerService::Client::disconnectNativeWindow_l() {
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700903 if (mConnectedWindow != NULL) {
Chong Zhang181fd9b2017-02-16 15:53:03 -0800904 status_t err = nativeWindowDisconnect(
905 mConnectedWindow.get(), "disconnectNativeWindow");
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700906
907 if (err != OK) {
Chong Zhang181fd9b2017-02-16 15:53:03 -0800908 ALOGW("nativeWindowDisconnect returned an error: %s (%d)",
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700909 strerror(-err), err);
910 }
911 }
912 mConnectedWindow.clear();
913}
914
Glenn Kasten11731182011-02-08 17:26:17 -0800915status_t MediaPlayerService::Client::setVideoSurfaceTexture(
Andy McFadden484566c2012-12-18 09:46:54 -0800916 const sp<IGraphicBufferProducer>& bufferProducer)
Glenn Kasten11731182011-02-08 17:26:17 -0800917{
Andy McFadden484566c2012-12-18 09:46:54 -0800918 ALOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, bufferProducer.get());
Glenn Kasten11731182011-02-08 17:26:17 -0800919 sp<MediaPlayerBase> p = getPlayer();
920 if (p == 0) return UNKNOWN_ERROR;
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700921
Marco Nelissenf8880202014-11-14 07:58:25 -0800922 sp<IBinder> binder(IInterface::asBinder(bufferProducer));
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700923 if (mConnectedWindowBinder == binder) {
924 return OK;
925 }
926
927 sp<ANativeWindow> anw;
Andy McFadden484566c2012-12-18 09:46:54 -0800928 if (bufferProducer != NULL) {
Marco Nelissenee08f7e2013-09-16 13:30:01 -0700929 anw = new Surface(bufferProducer, true /* controlledByApp */);
Chong Zhang181fd9b2017-02-16 15:53:03 -0800930 status_t err = nativeWindowConnect(anw.get(), "setVideoSurfaceTexture");
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700931
932 if (err != OK) {
Steve Block29357bc2012-01-06 19:20:56 +0000933 ALOGE("setVideoSurfaceTexture failed: %d", err);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700934 // Note that we must do the reset before disconnecting from the ANW.
935 // Otherwise queue/dequeue calls could be made on the disconnected
936 // ANW, which may result in errors.
937 reset();
938
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700939 Mutex::Autolock lock(mLock);
940 disconnectNativeWindow_l();
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700941
942 return err;
943 }
944 }
945
Andy McFadden484566c2012-12-18 09:46:54 -0800946 // Note that we must set the player's new GraphicBufferProducer before
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700947 // disconnecting the old one. Otherwise queue/dequeue calls could be made
948 // on the disconnected ANW, which may result in errors.
Andy McFadden484566c2012-12-18 09:46:54 -0800949 status_t err = p->setVideoSurfaceTexture(bufferProducer);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700950
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700951 mLock.lock();
952 disconnectNativeWindow_l();
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700953
954 if (err == OK) {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700955 mConnectedWindow = anw;
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700956 mConnectedWindowBinder = binder;
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700957 mLock.unlock();
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700958 } else {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700959 mLock.unlock();
960 status_t err = nativeWindowDisconnect(
961 anw.get(), "disconnectNativeWindow");
962
963 if (err != OK) {
964 ALOGW("nativeWindowDisconnect returned an error: %s (%d)",
965 strerror(-err), err);
966 }
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700967 }
968
969 return err;
Glenn Kasten11731182011-02-08 17:26:17 -0800970}
971
Nicolas Catania1d187f12009-05-12 23:25:55 -0700972status_t MediaPlayerService::Client::invoke(const Parcel& request,
973 Parcel *reply)
974{
975 sp<MediaPlayerBase> p = getPlayer();
976 if (p == NULL) return UNKNOWN_ERROR;
977 return p->invoke(request, reply);
978}
979
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700980// This call doesn't need to access the native player.
981status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
982{
983 status_t status;
nikoa64c8c72009-07-20 15:07:26 -0700984 media::Metadata::Filter allow, drop;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700985
Nicolas Catania48290382009-07-10 13:53:06 -0700986 if (unmarshallFilter(filter, &allow, &status) &&
987 unmarshallFilter(filter, &drop, &status)) {
988 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700989
990 mMetadataAllow = allow;
991 mMetadataDrop = drop;
992 }
993 return status;
994}
995
Nicolas Catania48290382009-07-10 13:53:06 -0700996status_t MediaPlayerService::Client::getMetadata(
Mark Salyzyn77342f72014-06-18 16:31:32 -0700997 bool update_only, bool /*apply_filter*/, Parcel *reply)
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700998{
nikoa64c8c72009-07-20 15:07:26 -0700999 sp<MediaPlayerBase> player = getPlayer();
1000 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania48290382009-07-10 13:53:06 -07001001
nikod608a812009-07-16 16:39:53 -07001002 status_t status;
1003 // Placeholder for the return code, updated by the caller.
1004 reply->writeInt32(-1);
1005
nikoa64c8c72009-07-20 15:07:26 -07001006 media::Metadata::Filter ids;
Nicolas Catania48290382009-07-10 13:53:06 -07001007
1008 // We don't block notifications while we fetch the data. We clear
1009 // mMetadataUpdated first so we don't lose notifications happening
1010 // during the rest of this call.
1011 {
1012 Mutex::Autolock lock(mLock);
1013 if (update_only) {
nikod608a812009-07-16 16:39:53 -07001014 ids = mMetadataUpdated;
Nicolas Catania48290382009-07-10 13:53:06 -07001015 }
1016 mMetadataUpdated.clear();
1017 }
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001018
nikoa64c8c72009-07-20 15:07:26 -07001019 media::Metadata metadata(reply);
Nicolas Catania48290382009-07-10 13:53:06 -07001020
nikoa64c8c72009-07-20 15:07:26 -07001021 metadata.appendHeader();
1022 status = player->getMetadata(ids, reply);
nikod608a812009-07-16 16:39:53 -07001023
1024 if (status != OK) {
nikoa64c8c72009-07-20 15:07:26 -07001025 metadata.resetParcel();
Steve Block29357bc2012-01-06 19:20:56 +00001026 ALOGE("getMetadata failed %d", status);
nikod608a812009-07-16 16:39:53 -07001027 return status;
1028 }
1029
1030 // FIXME: Implement filtering on the result. Not critical since
1031 // filtering takes place on the update notifications already. This
1032 // would be when all the metadata are fetch and a filter is set.
1033
nikod608a812009-07-16 16:39:53 -07001034 // Everything is fine, update the metadata length.
nikoa64c8c72009-07-20 15:07:26 -07001035 metadata.updateLength();
nikod608a812009-07-16 16:39:53 -07001036 return OK;
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001037}
1038
Wei Jiad399e7e2016-10-26 15:49:11 -07001039status_t MediaPlayerService::Client::setBufferingSettings(
1040 const BufferingSettings& buffering)
1041{
Wei Jiadc6f3402017-01-09 15:04:18 -08001042 ALOGV("[%d] setBufferingSettings{%s}",
1043 mConnId, buffering.toString().string());
Wei Jiad399e7e2016-10-26 15:49:11 -07001044 sp<MediaPlayerBase> p = getPlayer();
1045 if (p == 0) return UNKNOWN_ERROR;
1046 return p->setBufferingSettings(buffering);
1047}
1048
Wei Jia9bb38032017-03-23 18:00:38 -07001049status_t MediaPlayerService::Client::getBufferingSettings(
Wei Jiad399e7e2016-10-26 15:49:11 -07001050 BufferingSettings* buffering /* nonnull */)
1051{
1052 sp<MediaPlayerBase> p = getPlayer();
1053 // TODO: create mPlayer on demand.
1054 if (p == 0) return UNKNOWN_ERROR;
Wei Jia9bb38032017-03-23 18:00:38 -07001055 status_t ret = p->getBufferingSettings(buffering);
Wei Jiad399e7e2016-10-26 15:49:11 -07001056 if (ret == NO_ERROR) {
Wei Jia9bb38032017-03-23 18:00:38 -07001057 ALOGV("[%d] getBufferingSettings{%s}",
Wei Jiadc6f3402017-01-09 15:04:18 -08001058 mConnId, buffering->toString().string());
Wei Jiad399e7e2016-10-26 15:49:11 -07001059 } else {
Wei Jia9bb38032017-03-23 18:00:38 -07001060 ALOGE("[%d] getBufferingSettings returned %d", mConnId, ret);
Wei Jiad399e7e2016-10-26 15:49:11 -07001061 }
1062 return ret;
1063}
1064
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001065status_t MediaPlayerService::Client::prepareAsync()
1066{
Steve Block3856b092011-10-20 11:56:00 +01001067 ALOGV("[%d] prepareAsync", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001068 sp<MediaPlayerBase> p = getPlayer();
1069 if (p == 0) return UNKNOWN_ERROR;
1070 status_t ret = p->prepareAsync();
1071#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +00001072 ALOGD("start Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001073 if (ret == NO_ERROR) mAntagonizer->start();
1074#endif
1075 return ret;
1076}
1077
1078status_t MediaPlayerService::Client::start()
1079{
Steve Block3856b092011-10-20 11:56:00 +01001080 ALOGV("[%d] start", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001081 sp<MediaPlayerBase> p = getPlayer();
1082 if (p == 0) return UNKNOWN_ERROR;
1083 p->setLooping(mLoop);
1084 return p->start();
1085}
1086
1087status_t MediaPlayerService::Client::stop()
1088{
Steve Block3856b092011-10-20 11:56:00 +01001089 ALOGV("[%d] stop", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001090 sp<MediaPlayerBase> p = getPlayer();
1091 if (p == 0) return UNKNOWN_ERROR;
1092 return p->stop();
1093}
1094
1095status_t MediaPlayerService::Client::pause()
1096{
Steve Block3856b092011-10-20 11:56:00 +01001097 ALOGV("[%d] pause", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001098 sp<MediaPlayerBase> p = getPlayer();
1099 if (p == 0) return UNKNOWN_ERROR;
1100 return p->pause();
1101}
1102
1103status_t MediaPlayerService::Client::isPlaying(bool* state)
1104{
1105 *state = false;
1106 sp<MediaPlayerBase> p = getPlayer();
1107 if (p == 0) return UNKNOWN_ERROR;
1108 *state = p->isPlaying();
Steve Block3856b092011-10-20 11:56:00 +01001109 ALOGV("[%d] isPlaying: %d", mConnId, *state);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001110 return NO_ERROR;
1111}
1112
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001113status_t MediaPlayerService::Client::setPlaybackSettings(const AudioPlaybackRate& rate)
Wei Jia98160162015-02-04 17:01:11 -08001114{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001115 ALOGV("[%d] setPlaybackSettings(%f, %f, %d, %d)",
1116 mConnId, rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Wei Jia98160162015-02-04 17:01:11 -08001117 sp<MediaPlayerBase> p = getPlayer();
1118 if (p == 0) return UNKNOWN_ERROR;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001119 return p->setPlaybackSettings(rate);
1120}
1121
1122status_t MediaPlayerService::Client::getPlaybackSettings(AudioPlaybackRate* rate /* nonnull */)
1123{
1124 sp<MediaPlayerBase> p = getPlayer();
1125 if (p == 0) return UNKNOWN_ERROR;
1126 status_t ret = p->getPlaybackSettings(rate);
1127 if (ret == NO_ERROR) {
1128 ALOGV("[%d] getPlaybackSettings(%f, %f, %d, %d)",
1129 mConnId, rate->mSpeed, rate->mPitch, rate->mFallbackMode, rate->mStretchMode);
1130 } else {
1131 ALOGV("[%d] getPlaybackSettings returned %d", mConnId, ret);
1132 }
1133 return ret;
1134}
1135
1136status_t MediaPlayerService::Client::setSyncSettings(
1137 const AVSyncSettings& sync, float videoFpsHint)
1138{
1139 ALOGV("[%d] setSyncSettings(%u, %u, %f, %f)",
1140 mConnId, sync.mSource, sync.mAudioAdjustMode, sync.mTolerance, videoFpsHint);
1141 sp<MediaPlayerBase> p = getPlayer();
1142 if (p == 0) return UNKNOWN_ERROR;
1143 return p->setSyncSettings(sync, videoFpsHint);
1144}
1145
1146status_t MediaPlayerService::Client::getSyncSettings(
1147 AVSyncSettings* sync /* nonnull */, float* videoFps /* nonnull */)
1148{
1149 sp<MediaPlayerBase> p = getPlayer();
1150 if (p == 0) return UNKNOWN_ERROR;
1151 status_t ret = p->getSyncSettings(sync, videoFps);
1152 if (ret == NO_ERROR) {
1153 ALOGV("[%d] getSyncSettings(%u, %u, %f, %f)",
1154 mConnId, sync->mSource, sync->mAudioAdjustMode, sync->mTolerance, *videoFps);
1155 } else {
1156 ALOGV("[%d] getSyncSettings returned %d", mConnId, ret);
1157 }
1158 return ret;
Wei Jia98160162015-02-04 17:01:11 -08001159}
1160
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001161status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
1162{
Steve Block3856b092011-10-20 11:56:00 +01001163 ALOGV("getCurrentPosition");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001164 sp<MediaPlayerBase> p = getPlayer();
1165 if (p == 0) return UNKNOWN_ERROR;
1166 status_t ret = p->getCurrentPosition(msec);
1167 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001168 ALOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001169 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001170 ALOGE("getCurrentPosition returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001171 }
1172 return ret;
1173}
1174
1175status_t MediaPlayerService::Client::getDuration(int *msec)
1176{
Steve Block3856b092011-10-20 11:56:00 +01001177 ALOGV("getDuration");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001178 sp<MediaPlayerBase> p = getPlayer();
1179 if (p == 0) return UNKNOWN_ERROR;
1180 status_t ret = p->getDuration(msec);
1181 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001182 ALOGV("[%d] getDuration = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001183 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001184 ALOGE("getDuration returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001185 }
1186 return ret;
1187}
1188
Marco Nelissen6b74d672012-02-28 16:07:44 -08001189status_t MediaPlayerService::Client::setNextPlayer(const sp<IMediaPlayer>& player) {
1190 ALOGV("setNextPlayer");
1191 Mutex::Autolock l(mLock);
1192 sp<Client> c = static_cast<Client*>(player.get());
Wei Jia28284122016-08-30 13:49:06 -07001193 if (c != NULL && !mService->hasClient(c)) {
Robert Shihee0a0e32016-08-16 16:50:54 -07001194 return BAD_VALUE;
1195 }
1196
Marco Nelissen6b74d672012-02-28 16:07:44 -08001197 mNextClient = c;
John Grossman5f7e55e2012-08-24 14:47:25 -07001198
1199 if (c != NULL) {
1200 if (mAudioOutput != NULL) {
1201 mAudioOutput->setNextOutput(c->mAudioOutput);
1202 } else if ((mPlayer != NULL) && !mPlayer->hardwareOutput()) {
1203 ALOGE("no current audio output");
1204 }
1205
1206 if ((mPlayer != NULL) && (mNextClient->getPlayer() != NULL)) {
1207 mPlayer->setNextPlayer(mNextClient->getPlayer());
1208 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001209 }
John Grossman5f7e55e2012-08-24 14:47:25 -07001210
Marco Nelissen6b74d672012-02-28 16:07:44 -08001211 return OK;
1212}
1213
Andy Hung9fc8b5c2017-01-24 13:36:48 -08001214VolumeShaper::Status MediaPlayerService::Client::applyVolumeShaper(
1215 const sp<VolumeShaper::Configuration>& configuration,
1216 const sp<VolumeShaper::Operation>& operation) {
1217 // for hardware output, call player instead
1218 ALOGV("Client::applyVolumeShaper(%p)", this);
1219 sp<MediaPlayerBase> p = getPlayer();
1220 {
1221 Mutex::Autolock l(mLock);
1222 if (p != 0 && p->hardwareOutput()) {
1223 // TODO: investigate internal implementation
1224 return VolumeShaper::Status(INVALID_OPERATION);
1225 }
1226 if (mAudioOutput.get() != nullptr) {
1227 return mAudioOutput->applyVolumeShaper(configuration, operation);
1228 }
1229 }
1230 return VolumeShaper::Status(INVALID_OPERATION);
1231}
1232
1233sp<VolumeShaper::State> MediaPlayerService::Client::getVolumeShaperState(int id) {
1234 // for hardware output, call player instead
1235 ALOGV("Client::getVolumeShaperState(%p)", this);
1236 sp<MediaPlayerBase> p = getPlayer();
1237 {
1238 Mutex::Autolock l(mLock);
1239 if (p != 0 && p->hardwareOutput()) {
1240 // TODO: investigate internal implementation.
1241 return nullptr;
1242 }
1243 if (mAudioOutput.get() != nullptr) {
1244 return mAudioOutput->getVolumeShaperState(id);
1245 }
1246 }
1247 return nullptr;
1248}
1249
Wei Jiac5de0912016-11-18 10:22:14 -08001250status_t MediaPlayerService::Client::seekTo(int msec, MediaPlayerSeekMode mode)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001251{
Wei Jiac5de0912016-11-18 10:22:14 -08001252 ALOGV("[%d] seekTo(%d, %d)", mConnId, msec, mode);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001253 sp<MediaPlayerBase> p = getPlayer();
1254 if (p == 0) return UNKNOWN_ERROR;
Wei Jiac5de0912016-11-18 10:22:14 -08001255 return p->seekTo(msec, mode);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001256}
1257
1258status_t MediaPlayerService::Client::reset()
1259{
Steve Block3856b092011-10-20 11:56:00 +01001260 ALOGV("[%d] reset", mConnId);
John Grossmanc795b642012-02-22 15:38:35 -08001261 mRetransmitEndpointValid = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001262 sp<MediaPlayerBase> p = getPlayer();
1263 if (p == 0) return UNKNOWN_ERROR;
1264 return p->reset();
1265}
1266
Wei Jia52c28512017-09-13 18:17:51 -07001267status_t MediaPlayerService::Client::notifyAt(int64_t mediaTimeUs)
1268{
1269 ALOGV("[%d] notifyAt(%lld)", mConnId, (long long)mediaTimeUs);
1270 sp<MediaPlayerBase> p = getPlayer();
1271 if (p == 0) return UNKNOWN_ERROR;
1272 return p->notifyAt(mediaTimeUs);
1273}
1274
Glenn Kastenfff6d712012-01-12 16:38:12 -08001275status_t MediaPlayerService::Client::setAudioStreamType(audio_stream_type_t type)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001276{
Steve Block3856b092011-10-20 11:56:00 +01001277 ALOGV("[%d] setAudioStreamType(%d)", mConnId, type);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001278 // TODO: for hardware output, call player instead
1279 Mutex::Autolock l(mLock);
1280 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1281 return NO_ERROR;
1282}
1283
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001284status_t MediaPlayerService::Client::setAudioAttributes_l(const Parcel &parcel)
1285{
1286 if (mAudioAttributes != NULL) { free(mAudioAttributes); }
1287 mAudioAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001288 if (mAudioAttributes == NULL) {
1289 return NO_MEMORY;
1290 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001291 unmarshallAudioAttributes(parcel, mAudioAttributes);
1292
1293 ALOGV("setAudioAttributes_l() usage=%d content=%d flags=0x%x tags=%s",
1294 mAudioAttributes->usage, mAudioAttributes->content_type, mAudioAttributes->flags,
1295 mAudioAttributes->tags);
1296
1297 if (mAudioOutput != 0) {
1298 mAudioOutput->setAudioAttributes(mAudioAttributes);
1299 }
1300 return NO_ERROR;
1301}
1302
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001303status_t MediaPlayerService::Client::setLooping(int loop)
1304{
Steve Block3856b092011-10-20 11:56:00 +01001305 ALOGV("[%d] setLooping(%d)", mConnId, loop);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001306 mLoop = loop;
1307 sp<MediaPlayerBase> p = getPlayer();
1308 if (p != 0) return p->setLooping(loop);
1309 return NO_ERROR;
1310}
1311
1312status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1313{
Steve Block3856b092011-10-20 11:56:00 +01001314 ALOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
John Grossman761defc2012-02-09 15:09:05 -08001315
1316 // for hardware output, call player instead
1317 sp<MediaPlayerBase> p = getPlayer();
1318 {
1319 Mutex::Autolock l(mLock);
1320 if (p != 0 && p->hardwareOutput()) {
1321 MediaPlayerHWInterface* hwp =
1322 reinterpret_cast<MediaPlayerHWInterface*>(p.get());
1323 return hwp->setVolume(leftVolume, rightVolume);
1324 } else {
1325 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1326 return NO_ERROR;
1327 }
1328 }
1329
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001330 return NO_ERROR;
1331}
1332
Eric Laurent2beeb502010-07-16 07:43:46 -07001333status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1334{
Steve Block3856b092011-10-20 11:56:00 +01001335 ALOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
Eric Laurent2beeb502010-07-16 07:43:46 -07001336 Mutex::Autolock l(mLock);
1337 if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1338 return NO_ERROR;
1339}
1340
1341status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1342{
Steve Block3856b092011-10-20 11:56:00 +01001343 ALOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
Eric Laurent2beeb502010-07-16 07:43:46 -07001344 Mutex::Autolock l(mLock);
1345 if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1346 return NO_ERROR;
1347}
Nicolas Catania48290382009-07-10 13:53:06 -07001348
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001349status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
Steve Block3856b092011-10-20 11:56:00 +01001350 ALOGV("[%d] setParameter(%d)", mConnId, key);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001351 switch (key) {
1352 case KEY_PARAMETER_AUDIO_ATTRIBUTES:
1353 {
1354 Mutex::Autolock l(mLock);
1355 return setAudioAttributes_l(request);
1356 }
1357 default:
1358 sp<MediaPlayerBase> p = getPlayer();
1359 if (p == 0) { return UNKNOWN_ERROR; }
1360 return p->setParameter(key, request);
1361 }
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001362}
1363
1364status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
Steve Block3856b092011-10-20 11:56:00 +01001365 ALOGV("[%d] getParameter(%d)", mConnId, key);
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001366 sp<MediaPlayerBase> p = getPlayer();
1367 if (p == 0) return UNKNOWN_ERROR;
1368 return p->getParameter(key, reply);
1369}
1370
John Grossmanc795b642012-02-22 15:38:35 -08001371status_t MediaPlayerService::Client::setRetransmitEndpoint(
1372 const struct sockaddr_in* endpoint) {
1373
1374 if (NULL != endpoint) {
1375 uint32_t a = ntohl(endpoint->sin_addr.s_addr);
1376 uint16_t p = ntohs(endpoint->sin_port);
1377 ALOGV("[%d] setRetransmitEndpoint(%u.%u.%u.%u:%hu)", mConnId,
1378 (a >> 24), (a >> 16) & 0xFF, (a >> 8) & 0xFF, (a & 0xFF), p);
1379 } else {
1380 ALOGV("[%d] setRetransmitEndpoint = <none>", mConnId);
1381 }
1382
1383 sp<MediaPlayerBase> p = getPlayer();
1384
1385 // Right now, the only valid time to set a retransmit endpoint is before
1386 // player selection has been made (since the presence or absence of a
1387 // retransmit endpoint is going to determine which player is selected during
1388 // setDataSource).
1389 if (p != 0) return INVALID_OPERATION;
1390
1391 if (NULL != endpoint) {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001392 Mutex::Autolock lock(mLock);
John Grossmanc795b642012-02-22 15:38:35 -08001393 mRetransmitEndpoint = *endpoint;
1394 mRetransmitEndpointValid = true;
1395 } else {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001396 Mutex::Autolock lock(mLock);
John Grossmanc795b642012-02-22 15:38:35 -08001397 mRetransmitEndpointValid = false;
1398 }
1399
1400 return NO_ERROR;
1401}
1402
John Grossman44a7e422012-06-21 17:29:24 -07001403status_t MediaPlayerService::Client::getRetransmitEndpoint(
1404 struct sockaddr_in* endpoint)
1405{
1406 if (NULL == endpoint)
1407 return BAD_VALUE;
1408
1409 sp<MediaPlayerBase> p = getPlayer();
1410
1411 if (p != NULL)
1412 return p->getRetransmitEndpoint(endpoint);
1413
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001414 Mutex::Autolock lock(mLock);
John Grossman44a7e422012-06-21 17:29:24 -07001415 if (!mRetransmitEndpointValid)
1416 return NO_INIT;
1417
1418 *endpoint = mRetransmitEndpoint;
1419
1420 return NO_ERROR;
1421}
1422
Gloria Wangb483c472011-04-11 17:23:27 -07001423void MediaPlayerService::Client::notify(
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001424 int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001425{
James Dongb8a98252012-08-26 16:13:03 -07001426 sp<IMediaPlayerClient> c;
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001427 sp<Client> nextClient;
1428 status_t errStartNext = NO_ERROR;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001429 {
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001430 Mutex::Autolock l(mLock);
1431 c = mClient;
1432 if (msg == MEDIA_PLAYBACK_COMPLETE && mNextClient != NULL) {
1433 nextClient = mNextClient;
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001434
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001435 if (mAudioOutput != NULL)
1436 mAudioOutput->switchToNextOutput();
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001437
1438 errStartNext = nextClient->start();
1439 }
1440 }
1441
1442 if (nextClient != NULL) {
1443 sp<IMediaPlayerClient> nc;
1444 {
1445 Mutex::Autolock l(nextClient->mLock);
1446 nc = nextClient->mClient;
1447 }
1448 if (nc != NULL) {
1449 if (errStartNext == NO_ERROR) {
1450 nc->notify(MEDIA_INFO, MEDIA_INFO_STARTED_AS_NEXT, 0, obj);
1451 } else {
1452 nc->notify(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN , 0, obj);
1453 ALOGE("gapless:start playback for next track failed, err(%d)", errStartNext);
Wei Jia2afac0c2016-01-07 12:13:07 -08001454 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001455 }
1456 }
1457
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001458 if (MEDIA_INFO == msg &&
Nicolas Catania48290382009-07-10 13:53:06 -07001459 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikoa64c8c72009-07-20 15:07:26 -07001460 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania48290382009-07-10 13:53:06 -07001461
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001462 if(shouldDropMetadata(metadata_type)) {
Nicolas Catania48290382009-07-10 13:53:06 -07001463 return;
1464 }
1465
1466 // Update the list of metadata that have changed. getMetadata
1467 // also access mMetadataUpdated and clears it.
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001468 addNewMetadataUpdate(metadata_type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001469 }
James Dongb8a98252012-08-26 16:13:03 -07001470
1471 if (c != NULL) {
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001472 ALOGV("[%d] notify (%d, %d, %d)", mConnId, msg, ext1, ext2);
James Dongb8a98252012-08-26 16:13:03 -07001473 c->notify(msg, ext1, ext2, obj);
1474 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001475}
1476
Nicolas Catania48290382009-07-10 13:53:06 -07001477
nikoa64c8c72009-07-20 15:07:26 -07001478bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001479{
Nicolas Catania48290382009-07-10 13:53:06 -07001480 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001481
Nicolas Catania48290382009-07-10 13:53:06 -07001482 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001483 return true;
1484 }
1485
Nicolas Catania48290382009-07-10 13:53:06 -07001486 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001487 return false;
Nicolas Catania48290382009-07-10 13:53:06 -07001488 } else {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001489 return true;
1490 }
1491}
1492
Nicolas Catania48290382009-07-10 13:53:06 -07001493
nikoa64c8c72009-07-20 15:07:26 -07001494void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania48290382009-07-10 13:53:06 -07001495 Mutex::Autolock lock(mLock);
1496 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1497 mMetadataUpdated.add(metadata_type);
1498 }
1499}
1500
Hassan Shojaniacefac142017-02-06 21:02:02 -08001501// Modular DRM
1502status_t MediaPlayerService::Client::prepareDrm(const uint8_t uuid[16],
1503 const Vector<uint8_t>& drmSessionId)
1504{
1505 ALOGV("[%d] prepareDrm", mConnId);
1506 sp<MediaPlayerBase> p = getPlayer();
1507 if (p == 0) return UNKNOWN_ERROR;
1508
1509 status_t ret = p->prepareDrm(uuid, drmSessionId);
1510 ALOGV("prepareDrm ret: %d", ret);
1511
1512 return ret;
1513}
1514
1515status_t MediaPlayerService::Client::releaseDrm()
1516{
1517 ALOGV("[%d] releaseDrm", mConnId);
1518 sp<MediaPlayerBase> p = getPlayer();
1519 if (p == 0) return UNKNOWN_ERROR;
1520
1521 status_t ret = p->releaseDrm();
1522 ALOGV("releaseDrm ret: %d", ret);
1523
1524 return ret;
1525}
1526
jiabin156c6872017-10-06 09:47:15 -07001527status_t MediaPlayerService::Client::setOutputDevice(audio_port_handle_t deviceId)
1528{
1529 ALOGV("[%d] setOutputDevice", mConnId);
1530 {
1531 Mutex::Autolock l(mLock);
1532 if (mAudioOutput.get() != nullptr) {
1533 return mAudioOutput->setOutputDevice(deviceId);
1534 }
1535 }
1536 return NO_INIT;
1537}
1538
1539status_t MediaPlayerService::Client::getRoutedDeviceId(audio_port_handle_t* deviceId)
1540{
1541 ALOGV("[%d] getRoutedDeviceId", mConnId);
1542 {
1543 Mutex::Autolock l(mLock);
1544 if (mAudioOutput.get() != nullptr) {
1545 return mAudioOutput->getRoutedDeviceId(deviceId);
1546 }
1547 }
1548 return NO_INIT;
1549}
1550
1551status_t MediaPlayerService::Client::enableAudioDeviceCallback(bool enabled)
1552{
1553 ALOGV("[%d] enableAudioDeviceCallback, %d", mConnId, enabled);
1554 {
1555 Mutex::Autolock l(mLock);
1556 if (mAudioOutput.get() != nullptr) {
1557 return mAudioOutput->enableAudioDeviceCallback(enabled);
1558 }
1559 }
1560 return NO_INIT;
1561}
1562
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001563#if CALLBACK_ANTAGONIZER
1564const int Antagonizer::interval = 10000; // 10 msecs
1565
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001566Antagonizer::Antagonizer(const sp<MediaPlayerBase::Listener> &listener) :
1567 mExit(false), mActive(false), mListener(listener)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001568{
1569 createThread(callbackThread, this);
1570}
1571
1572void Antagonizer::kill()
1573{
1574 Mutex::Autolock _l(mLock);
1575 mActive = false;
1576 mExit = true;
1577 mCondition.wait(mLock);
1578}
1579
1580int Antagonizer::callbackThread(void* user)
1581{
Steve Blockb8a80522011-12-20 16:23:08 +00001582 ALOGD("Antagonizer started");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001583 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1584 while (!p->mExit) {
1585 if (p->mActive) {
Steve Block3856b092011-10-20 11:56:00 +01001586 ALOGV("send event");
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001587 p->mListener->notify(0, 0, 0, 0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001588 }
1589 usleep(interval);
1590 }
1591 Mutex::Autolock _l(p->mLock);
1592 p->mCondition.signal();
Steve Blockb8a80522011-12-20 16:23:08 +00001593 ALOGD("Antagonizer stopped");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001594 return 0;
1595}
1596#endif
1597
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001598#undef LOG_TAG
1599#define LOG_TAG "AudioSink"
Andy Hung1afd0982016-11-08 16:13:44 -08001600MediaPlayerService::AudioOutput::AudioOutput(audio_session_t sessionId, uid_t uid, int pid,
jiabin156c6872017-10-06 09:47:15 -07001601 const audio_attributes_t* attr, const sp<AudioSystem::AudioDeviceCallback>& deviceCallback)
Andreas Huber20111aa2009-07-14 16:56:47 -07001602 : mCallback(NULL),
Eric Laurenta514bdb2010-06-21 09:27:30 -07001603 mCallbackCookie(NULL),
Marco Nelissen6b74d672012-02-28 16:07:44 -08001604 mCallbackData(NULL),
Andy Hungd1c74342015-07-07 16:54:23 -07001605 mStreamType(AUDIO_STREAM_MUSIC),
Andy Hungd1c74342015-07-07 16:54:23 -07001606 mLeftVolume(1.0),
1607 mRightVolume(1.0),
1608 mPlaybackRate(AUDIO_PLAYBACK_RATE_DEFAULT),
1609 mSampleRateHz(0),
1610 mMsecsPerFrame(0),
1611 mFrameSize(0),
Eric Laurent1948eb32012-04-13 16:50:19 -07001612 mSessionId(sessionId),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001613 mUid(uid),
Marco Nelissend457c972014-02-11 08:47:07 -08001614 mPid(pid),
Andy Hungd1c74342015-07-07 16:54:23 -07001615 mSendLevel(0.0),
1616 mAuxEffectId(0),
Andy Hung4ef88d72017-02-21 19:47:53 -08001617 mFlags(AUDIO_OUTPUT_FLAG_NONE),
jiabin156c6872017-10-06 09:47:15 -07001618 mVolumeHandler(new media::VolumeHandler()),
1619 mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE),
jiabin161b64f2017-11-17 09:31:48 -08001620 mRoutedDeviceId(AUDIO_PORT_HANDLE_NONE),
jiabin156c6872017-10-06 09:47:15 -07001621 mDeviceCallbackEnabled(false),
1622 mDeviceCallback(deviceCallback)
Andy Hungd1c74342015-07-07 16:54:23 -07001623{
Steve Block3856b092011-10-20 11:56:00 +01001624 ALOGV("AudioOutput(%d)", sessionId);
Eric Laurent43562692015-07-15 16:49:07 -07001625 if (attr != NULL) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001626 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1627 if (mAttributes != NULL) {
1628 memcpy(mAttributes, attr, sizeof(audio_attributes_t));
François Gaffie58d4be52018-11-06 15:30:12 +01001629 mStreamType = AudioSystem::attributesToStreamType(*attr);
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001630 }
1631 } else {
1632 mAttributes = NULL;
Eric Laurent43562692015-07-15 16:49:07 -07001633 }
1634
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001635 setMinBufferCount();
1636}
1637
1638MediaPlayerService::AudioOutput::~AudioOutput()
1639{
1640 close();
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001641 free(mAttributes);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001642 delete mCallbackData;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001643}
1644
Andy Hungd1c74342015-07-07 16:54:23 -07001645//static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001646void MediaPlayerService::AudioOutput::setMinBufferCount()
1647{
1648 char value[PROPERTY_VALUE_MAX];
1649 if (property_get("ro.kernel.qemu", value, 0)) {
1650 mIsOnEmulator = true;
1651 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1652 }
1653}
1654
Andy Hungd1c74342015-07-07 16:54:23 -07001655// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001656bool MediaPlayerService::AudioOutput::isOnEmulator()
1657{
Andy Hungd1c74342015-07-07 16:54:23 -07001658 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001659 return mIsOnEmulator;
1660}
1661
Andy Hungd1c74342015-07-07 16:54:23 -07001662// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001663int MediaPlayerService::AudioOutput::getMinBufferCount()
1664{
Andy Hungd1c74342015-07-07 16:54:23 -07001665 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001666 return mMinBufferCount;
1667}
1668
1669ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1670{
Andy Hungd1c74342015-07-07 16:54:23 -07001671 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001672 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001673 return mTrack->frameCount() * mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001674}
1675
1676ssize_t MediaPlayerService::AudioOutput::frameCount() const
1677{
Andy Hungd1c74342015-07-07 16:54:23 -07001678 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001679 if (mTrack == 0) return NO_INIT;
1680 return mTrack->frameCount();
1681}
1682
1683ssize_t MediaPlayerService::AudioOutput::channelCount() const
1684{
Andy Hungd1c74342015-07-07 16:54:23 -07001685 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001686 if (mTrack == 0) return NO_INIT;
1687 return mTrack->channelCount();
1688}
1689
1690ssize_t MediaPlayerService::AudioOutput::frameSize() const
1691{
Andy Hungd1c74342015-07-07 16:54:23 -07001692 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001693 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001694 return mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001695}
1696
1697uint32_t MediaPlayerService::AudioOutput::latency () const
1698{
Andy Hungd1c74342015-07-07 16:54:23 -07001699 Mutex::Autolock lock(mLock);
Eric Laurentdb354e52012-03-05 17:27:11 -08001700 if (mTrack == 0) return 0;
1701 return mTrack->latency();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001702}
1703
1704float MediaPlayerService::AudioOutput::msecsPerFrame() const
1705{
Andy Hungd1c74342015-07-07 16:54:23 -07001706 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001707 return mMsecsPerFrame;
1708}
1709
Marco Nelissen4110c102012-03-29 09:31:28 -07001710status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position) const
Eric Laurent342e9cf2010-01-19 17:37:09 -08001711{
Andy Hungd1c74342015-07-07 16:54:23 -07001712 Mutex::Autolock lock(mLock);
Eric Laurent342e9cf2010-01-19 17:37:09 -08001713 if (mTrack == 0) return NO_INIT;
1714 return mTrack->getPosition(position);
1715}
1716
Lajos Molnar06ad1522014-08-28 07:27:44 -07001717status_t MediaPlayerService::AudioOutput::getTimestamp(AudioTimestamp &ts) const
1718{
Andy Hungd1c74342015-07-07 16:54:23 -07001719 Mutex::Autolock lock(mLock);
Lajos Molnar06ad1522014-08-28 07:27:44 -07001720 if (mTrack == 0) return NO_INIT;
1721 return mTrack->getTimestamp(ts);
1722}
1723
Wei Jiac4ac8172015-10-21 10:35:48 -07001724// TODO: Remove unnecessary calls to getPlayedOutDurationUs()
1725// as it acquires locks and may query the audio driver.
1726//
1727// Some calls could conceivably retrieve extrapolated data instead of
1728// accessing getTimestamp() or getPosition() every time a data buffer with
1729// a media time is received.
1730//
1731// Calculate duration of played samples if played at normal rate (i.e., 1.0).
1732int64_t MediaPlayerService::AudioOutput::getPlayedOutDurationUs(int64_t nowUs) const
1733{
1734 Mutex::Autolock lock(mLock);
1735 if (mTrack == 0 || mSampleRateHz == 0) {
Wei Jia213f4902015-10-22 08:55:25 -07001736 return 0;
Wei Jiac4ac8172015-10-21 10:35:48 -07001737 }
1738
1739 uint32_t numFramesPlayed;
Andy Hung5d313802016-10-10 15:09:39 -07001740 int64_t numFramesPlayedAtUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001741 AudioTimestamp ts;
Wei Jiac4ac8172015-10-21 10:35:48 -07001742
1743 status_t res = mTrack->getTimestamp(ts);
1744 if (res == OK) { // case 1: mixing audio tracks and offloaded tracks.
1745 numFramesPlayed = ts.mPosition;
Andy Hung5d313802016-10-10 15:09:39 -07001746 numFramesPlayedAtUs = ts.mTime.tv_sec * 1000000LL + ts.mTime.tv_nsec / 1000;
1747 //ALOGD("getTimestamp: OK %d %lld", numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001748 } else if (res == WOULD_BLOCK) { // case 2: transitory state on start of a new track
1749 numFramesPlayed = 0;
Andy Hung5d313802016-10-10 15:09:39 -07001750 numFramesPlayedAtUs = nowUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001751 //ALOGD("getTimestamp: WOULD_BLOCK %d %lld",
Andy Hung5d313802016-10-10 15:09:39 -07001752 // numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001753 } else { // case 3: transitory at new track or audio fast tracks.
1754 res = mTrack->getPosition(&numFramesPlayed);
1755 CHECK_EQ(res, (status_t)OK);
Andy Hung5d313802016-10-10 15:09:39 -07001756 numFramesPlayedAtUs = nowUs;
1757 numFramesPlayedAtUs += 1000LL * mTrack->latency() / 2; /* XXX */
1758 //ALOGD("getPosition: %u %lld", numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001759 }
1760
1761 // CHECK_EQ(numFramesPlayed & (1 << 31), 0); // can't be negative until 12.4 hrs, test
1762 // TODO: remove the (int32_t) casting below as it may overflow at 12.4 hours.
1763 int64_t durationUs = (int64_t)((int32_t)numFramesPlayed * 1000000LL / mSampleRateHz)
Andy Hung5d313802016-10-10 15:09:39 -07001764 + nowUs - numFramesPlayedAtUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001765 if (durationUs < 0) {
1766 // Occurs when numFramesPlayed position is very small and the following:
1767 // (1) In case 1, the time nowUs is computed before getTimestamp() is called and
Andy Hung5d313802016-10-10 15:09:39 -07001768 // numFramesPlayedAtUs is greater than nowUs by time more than numFramesPlayed.
Wei Jiac4ac8172015-10-21 10:35:48 -07001769 // (2) In case 3, using getPosition and adding mAudioSink->latency() to
Andy Hung5d313802016-10-10 15:09:39 -07001770 // numFramesPlayedAtUs, by a time amount greater than numFramesPlayed.
Wei Jiac4ac8172015-10-21 10:35:48 -07001771 //
1772 // Both of these are transitory conditions.
1773 ALOGV("getPlayedOutDurationUs: negative duration %lld set to zero", (long long)durationUs);
1774 durationUs = 0;
1775 }
1776 ALOGV("getPlayedOutDurationUs(%lld) nowUs(%lld) frames(%u) framesAt(%lld)",
Andy Hung5d313802016-10-10 15:09:39 -07001777 (long long)durationUs, (long long)nowUs,
1778 numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001779 return durationUs;
1780}
1781
Marco Nelissen4110c102012-03-29 09:31:28 -07001782status_t MediaPlayerService::AudioOutput::getFramesWritten(uint32_t *frameswritten) const
1783{
Andy Hungd1c74342015-07-07 16:54:23 -07001784 Mutex::Autolock lock(mLock);
Marco Nelissen4110c102012-03-29 09:31:28 -07001785 if (mTrack == 0) return NO_INIT;
Andy Hung2f6e73d2016-04-08 12:12:58 -07001786 ExtendedTimestamp ets;
1787 status_t status = mTrack->getTimestamp(&ets);
1788 if (status == OK || status == WOULD_BLOCK) {
1789 *frameswritten = (uint32_t)ets.mPosition[ExtendedTimestamp::LOCATION_CLIENT];
1790 }
1791 return status;
Marco Nelissen4110c102012-03-29 09:31:28 -07001792}
1793
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001794status_t MediaPlayerService::AudioOutput::setParameters(const String8& keyValuePairs)
1795{
Andy Hungd1c74342015-07-07 16:54:23 -07001796 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001797 if (mTrack == 0) return NO_INIT;
1798 return mTrack->setParameters(keyValuePairs);
1799}
1800
1801String8 MediaPlayerService::AudioOutput::getParameters(const String8& keys)
1802{
Andy Hungd1c74342015-07-07 16:54:23 -07001803 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001804 if (mTrack == 0) return String8::empty();
1805 return mTrack->getParameters(keys);
1806}
1807
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001808void MediaPlayerService::AudioOutput::setAudioAttributes(const audio_attributes_t * attributes) {
Andy Hungd1c74342015-07-07 16:54:23 -07001809 Mutex::Autolock lock(mLock);
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001810 if (attributes == NULL) {
1811 free(mAttributes);
1812 mAttributes = NULL;
1813 } else {
1814 if (mAttributes == NULL) {
1815 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1816 }
1817 memcpy(mAttributes, attributes, sizeof(audio_attributes_t));
François Gaffie58d4be52018-11-06 15:30:12 +01001818 mStreamType = AudioSystem::attributesToStreamType(*attributes);
Eric Laurent43562692015-07-15 16:49:07 -07001819 }
1820}
1821
1822void MediaPlayerService::AudioOutput::setAudioStreamType(audio_stream_type_t streamType)
1823{
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001824 Mutex::Autolock lock(mLock);
Eric Laurent43562692015-07-15 16:49:07 -07001825 // do not allow direct stream type modification if attributes have been set
1826 if (mAttributes == NULL) {
1827 mStreamType = streamType;
1828 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001829}
1830
Andy Hungd1c74342015-07-07 16:54:23 -07001831void MediaPlayerService::AudioOutput::deleteRecycledTrack_l()
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001832{
Andy Hungd1c74342015-07-07 16:54:23 -07001833 ALOGV("deleteRecycledTrack_l");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001834 if (mRecycledTrack != 0) {
1835
1836 if (mCallbackData != NULL) {
1837 mCallbackData->setOutput(NULL);
1838 mCallbackData->endTrackSwitch();
1839 }
1840
1841 if ((mRecycledTrack->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) {
Andy Hunge13f8a62016-03-30 14:20:42 -07001842 int32_t msec = 0;
1843 if (!mRecycledTrack->stopped()) { // check if active
1844 (void)mRecycledTrack->pendingDuration(&msec);
1845 }
1846 mRecycledTrack->stop(); // ensure full data drain
1847 ALOGD("deleting recycled track, waiting for data drain (%d msec)", msec);
1848 if (msec > 0) {
1849 static const int32_t WAIT_LIMIT_MS = 3000;
1850 if (msec > WAIT_LIMIT_MS) {
1851 msec = WAIT_LIMIT_MS;
1852 }
1853 usleep(msec * 1000LL);
1854 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001855 }
1856 // An offloaded track isn't flushed because the STREAM_END is reported
1857 // slightly prematurely to allow time for the gapless track switch
1858 // but this means that if we decide not to recycle the track there
1859 // could be a small amount of residual data still playing. We leave
1860 // AudioFlinger to drain the track.
1861
1862 mRecycledTrack.clear();
Andy Hungd1c74342015-07-07 16:54:23 -07001863 close_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001864 delete mCallbackData;
1865 mCallbackData = NULL;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001866 }
1867}
1868
Andy Hungd1c74342015-07-07 16:54:23 -07001869void MediaPlayerService::AudioOutput::close_l()
1870{
1871 mTrack.clear();
1872}
1873
Andreas Huber20111aa2009-07-14 16:56:47 -07001874status_t MediaPlayerService::AudioOutput::open(
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001875 uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
1876 audio_format_t format, int bufferCount,
Eric Laurent1948eb32012-04-13 16:50:19 -07001877 AudioCallback cb, void *cookie,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001878 audio_output_flags_t flags,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001879 const audio_offload_info_t *offloadInfo,
Andy Hung179652e2015-05-31 22:49:46 -07001880 bool doNotReconnect,
1881 uint32_t suggestedFrameCount)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001882{
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001883 ALOGV("open(%u, %d, 0x%x, 0x%x, %d, %d 0x%x)", sampleRate, channelCount, channelMask,
1884 format, bufferCount, mSessionId, flags);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001885
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001886 // offloading is only supported in callback mode for now.
1887 // offloadInfo must be present if offload flag is set
1888 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) &&
1889 ((cb == NULL) || (offloadInfo == NULL))) {
1890 return BAD_VALUE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001891 }
1892
Andy Hung179652e2015-05-31 22:49:46 -07001893 // compute frame count for the AudioTrack internal buffer
1894 size_t frameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001895 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1896 frameCount = 0; // AudioTrack will get frame count from AudioFlinger
1897 } else {
Andy Hung179652e2015-05-31 22:49:46 -07001898 // try to estimate the buffer processing fetch size from AudioFlinger.
1899 // framesPerBuffer is approximate and generally correct, except when it's not :-).
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001900 uint32_t afSampleRate;
1901 size_t afFrameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001902 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1903 return NO_INIT;
1904 }
1905 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1906 return NO_INIT;
1907 }
Ben Romberger259fb462018-08-07 17:58:53 -07001908 if (afSampleRate == 0) {
1909 return NO_INIT;
1910 }
Andy Hung179652e2015-05-31 22:49:46 -07001911 const size_t framesPerBuffer =
1912 (unsigned long long)sampleRate * afFrameCount / afSampleRate;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001913
Andy Hung179652e2015-05-31 22:49:46 -07001914 if (bufferCount == 0) {
Ben Romberger259fb462018-08-07 17:58:53 -07001915 if (framesPerBuffer == 0) {
1916 return NO_INIT;
1917 }
Andy Hung179652e2015-05-31 22:49:46 -07001918 // use suggestedFrameCount
1919 bufferCount = (suggestedFrameCount + framesPerBuffer - 1) / framesPerBuffer;
1920 }
1921 // Check argument bufferCount against the mininum buffer count
1922 if (bufferCount != 0 && bufferCount < mMinBufferCount) {
1923 ALOGV("bufferCount (%d) increased to %d", bufferCount, mMinBufferCount);
1924 bufferCount = mMinBufferCount;
1925 }
1926 // if frameCount is 0, then AudioTrack will get frame count from AudioFlinger
1927 // which will be the minimum size permitted.
1928 frameCount = bufferCount * framesPerBuffer;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001929 }
Andreas Huber20111aa2009-07-14 16:56:47 -07001930
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001931 if (channelMask == CHANNEL_MASK_USE_CHANNEL_ORDER) {
Glenn Kastenab334fd2012-03-14 12:56:06 -07001932 channelMask = audio_channel_out_mask_from_count(channelCount);
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001933 if (0 == channelMask) {
1934 ALOGE("open() error, can\'t derive mask for %d audio channels", channelCount);
1935 return NO_INIT;
1936 }
1937 }
Eric Laurent1948eb32012-04-13 16:50:19 -07001938
Andy Hungd1c74342015-07-07 16:54:23 -07001939 Mutex::Autolock lock(mLock);
Andy Hung179652e2015-05-31 22:49:46 -07001940 mCallback = cb;
1941 mCallbackCookie = cookie;
1942
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001943 // Check whether we can recycle the track
1944 bool reuse = false;
1945 bool bothOffloaded = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001946
Glenn Kasten2799d742013-05-30 14:33:29 -07001947 if (mRecycledTrack != 0) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001948 // check whether we are switching between two offloaded tracks
1949 bothOffloaded = (flags & mRecycledTrack->getFlags()
1950 & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0;
Marco Nelissen67295b52012-06-11 14:52:53 -07001951
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001952 // check if the existing track can be reused as-is, or if a new track needs to be created.
1953 reuse = true;
1954
Marco Nelissen67295b52012-06-11 14:52:53 -07001955 if ((mCallbackData == NULL && mCallback != NULL) ||
1956 (mCallbackData != NULL && mCallback == NULL)) {
1957 // recycled track uses callbacks but the caller wants to use writes, or vice versa
1958 ALOGV("can't chain callback and write");
1959 reuse = false;
1960 } else if ((mRecycledTrack->getSampleRate() != sampleRate) ||
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001961 (mRecycledTrack->channelCount() != (uint32_t)channelCount) ) {
1962 ALOGV("samplerate, channelcount differ: %u/%u Hz, %u/%d ch",
Marco Nelissen67295b52012-06-11 14:52:53 -07001963 mRecycledTrack->getSampleRate(), sampleRate,
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001964 mRecycledTrack->channelCount(), channelCount);
Marco Nelissen67295b52012-06-11 14:52:53 -07001965 reuse = false;
1966 } else if (flags != mFlags) {
1967 ALOGV("output flags differ %08x/%08x", flags, mFlags);
1968 reuse = false;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001969 } else if (mRecycledTrack->format() != format) {
1970 reuse = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001971 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001972 } else {
1973 ALOGV("no track available to recycle");
1974 }
1975
1976 ALOGV_IF(bothOffloaded, "both tracks offloaded");
1977
1978 // If we can't recycle and both tracks are offloaded
1979 // we must close the previous output before opening a new one
1980 if (bothOffloaded && !reuse) {
1981 ALOGV("both offloaded and not recycling");
Andy Hungd1c74342015-07-07 16:54:23 -07001982 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001983 }
1984
1985 sp<AudioTrack> t;
1986 CallbackData *newcbd = NULL;
1987
1988 // We don't attempt to create a new track if we are recycling an
1989 // offloaded track. But, if we are recycling a non-offloaded or we
1990 // are switching where one is offloaded and one isn't then we create
1991 // the new track in advance so that we can read additional stream info
1992
1993 if (!(reuse && bothOffloaded)) {
1994 ALOGV("creating new AudioTrack");
1995
1996 if (mCallback != NULL) {
1997 newcbd = new CallbackData(this);
1998 t = new AudioTrack(
1999 mStreamType,
2000 sampleRate,
2001 format,
2002 channelMask,
2003 frameCount,
2004 flags,
2005 CallbackWrapper,
2006 newcbd,
2007 0, // notification frames
2008 mSessionId,
2009 AudioTrack::TRANSFER_CALLBACK,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002010 offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -08002011 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07002012 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07002013 mAttributes,
jiabin156c6872017-10-06 09:47:15 -07002014 doNotReconnect,
2015 1.0f, // default value for maxRequiredSpeed
2016 mSelectedDeviceId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002017 } else {
Andy Hungff874dc2016-04-11 16:49:09 -07002018 // TODO: Due to buffer memory concerns, we use a max target playback speed
2019 // based on mPlaybackRate at the time of open (instead of kMaxRequiredSpeed),
2020 // also clamping the target speed to 1.0 <= targetSpeed <= kMaxRequiredSpeed.
2021 const float targetSpeed =
2022 std::min(std::max(mPlaybackRate.mSpeed, 1.0f), kMaxRequiredSpeed);
2023 ALOGW_IF(targetSpeed != mPlaybackRate.mSpeed,
2024 "track target speed:%f clamped from playback speed:%f",
2025 targetSpeed, mPlaybackRate.mSpeed);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002026 t = new AudioTrack(
2027 mStreamType,
2028 sampleRate,
2029 format,
2030 channelMask,
2031 frameCount,
2032 flags,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002033 NULL, // callback
2034 NULL, // user data
2035 0, // notification frames
2036 mSessionId,
2037 AudioTrack::TRANSFER_DEFAULT,
2038 NULL, // offload info
Marco Nelissend457c972014-02-11 08:47:07 -08002039 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07002040 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07002041 mAttributes,
Andy Hungff874dc2016-04-11 16:49:09 -07002042 doNotReconnect,
jiabin156c6872017-10-06 09:47:15 -07002043 targetSpeed,
2044 mSelectedDeviceId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002045 }
2046
2047 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
2048 ALOGE("Unable to create audio track");
2049 delete newcbd;
Glenn Kasten3e98ecd2015-05-18 13:13:24 -07002050 // t goes out of scope, so reference count drops to zero
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002051 return NO_INIT;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07002052 } else {
2053 // successful AudioTrack initialization implies a legacy stream type was generated
2054 // from the audio attributes
2055 mStreamType = t->streamType();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002056 }
2057 }
2058
2059 if (reuse) {
2060 CHECK(mRecycledTrack != NULL);
2061
2062 if (!bothOffloaded) {
2063 if (mRecycledTrack->frameCount() != t->frameCount()) {
Andy Hung833b4752016-04-04 17:15:48 -07002064 ALOGV("framecount differs: %zu/%zu frames",
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002065 mRecycledTrack->frameCount(), t->frameCount());
2066 reuse = false;
2067 }
2068 }
2069
Marco Nelissen67295b52012-06-11 14:52:53 -07002070 if (reuse) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002071 ALOGV("chaining to next output and recycling track");
Andy Hungd1c74342015-07-07 16:54:23 -07002072 close_l();
Marco Nelissen67295b52012-06-11 14:52:53 -07002073 mTrack = mRecycledTrack;
Glenn Kasten2799d742013-05-30 14:33:29 -07002074 mRecycledTrack.clear();
Marco Nelissen67295b52012-06-11 14:52:53 -07002075 if (mCallbackData != NULL) {
2076 mCallbackData->setOutput(this);
2077 }
Marco Nelissen67295b52012-06-11 14:52:53 -07002078 delete newcbd;
Wei Jiae0bbac92016-07-18 16:04:53 -07002079 return updateTrack();
Marco Nelissen67295b52012-06-11 14:52:53 -07002080 }
Marco Nelissen67295b52012-06-11 14:52:53 -07002081 }
2082
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002083 // we're not going to reuse the track, unblock and flush it
2084 // this was done earlier if both tracks are offloaded
2085 if (!bothOffloaded) {
Andy Hungd1c74342015-07-07 16:54:23 -07002086 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002087 }
2088
2089 CHECK((t != NULL) && ((mCallback == NULL) || (newcbd != NULL)));
2090
Marco Nelissen67295b52012-06-11 14:52:53 -07002091 mCallbackData = newcbd;
Steve Block3856b092011-10-20 11:56:00 +01002092 ALOGV("setVolume");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002093 t->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07002094
Andy Hung39399b62017-04-21 15:07:45 -07002095 // Restore VolumeShapers for the MediaPlayer in case the track was recreated
2096 // due to an output sink error (e.g. offload to non-offload switch).
2097 mVolumeHandler->forall([&t](const VolumeShaper &shaper) -> VolumeShaper::Status {
2098 sp<VolumeShaper::Operation> operationToEnd =
2099 new VolumeShaper::Operation(shaper.mOperation);
2100 // TODO: Ideally we would restore to the exact xOffset position
2101 // as returned by getVolumeShaperState(), but we don't have that
2102 // information when restoring at the client unless we periodically poll
2103 // the server or create shared memory state.
2104 //
2105 // For now, we simply advance to the end of the VolumeShaper effect
2106 // if it has been started.
2107 if (shaper.isStarted()) {
Andy Hungf3702642017-05-05 17:33:32 -07002108 operationToEnd->setNormalizedTime(1.f);
Andy Hung39399b62017-04-21 15:07:45 -07002109 }
2110 return t->applyVolumeShaper(shaper.mConfiguration, operationToEnd);
Andy Hung4ef88d72017-02-21 19:47:53 -08002111 });
Andy Hung4ef88d72017-02-21 19:47:53 -08002112
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002113 mSampleRateHz = sampleRate;
Preetam Singh Ranawat2e17eef2015-08-12 12:11:46 -07002114 mFlags = flags;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002115 mMsecsPerFrame = 1E3f / (mPlaybackRate.mSpeed * sampleRate);
Andy Hungd1c74342015-07-07 16:54:23 -07002116 mFrameSize = t->frameSize();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002117 mTrack = t;
Eric Laurent2beeb502010-07-16 07:43:46 -07002118
Wei Jiae0bbac92016-07-18 16:04:53 -07002119 return updateTrack();
2120}
2121
2122status_t MediaPlayerService::AudioOutput::updateTrack() {
2123 if (mTrack == NULL) {
2124 return NO_ERROR;
2125 }
2126
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002127 status_t res = NO_ERROR;
Wei Jia0162d002015-06-09 11:59:33 -07002128 // Note some output devices may give us a direct track even though we don't specify it.
2129 // Example: Line application b/17459982.
Wei Jiae0bbac92016-07-18 16:04:53 -07002130 if ((mTrack->getFlags()
2131 & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) {
2132 res = mTrack->setPlaybackRate(mPlaybackRate);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002133 if (res == NO_ERROR) {
Wei Jiae0bbac92016-07-18 16:04:53 -07002134 mTrack->setAuxEffectSendLevel(mSendLevel);
2135 res = mTrack->attachAuxEffect(mAuxEffectId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002136 }
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002137 }
jiabin156c6872017-10-06 09:47:15 -07002138 mTrack->setOutputDevice(mSelectedDeviceId);
2139 if (mDeviceCallbackEnabled) {
2140 mTrack->addAudioDeviceCallback(mDeviceCallback.promote());
2141 }
Wei Jiae0bbac92016-07-18 16:04:53 -07002142 ALOGV("updateTrack() DONE status %d", res);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002143 return res;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002144}
2145
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002146status_t MediaPlayerService::AudioOutput::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002147{
Steve Block3856b092011-10-20 11:56:00 +01002148 ALOGV("start");
Andy Hungd1c74342015-07-07 16:54:23 -07002149 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08002150 if (mCallbackData != NULL) {
2151 mCallbackData->endTrackSwitch();
2152 }
Glenn Kasten2799d742013-05-30 14:33:29 -07002153 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002154 mTrack->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07002155 mTrack->setAuxEffectSendLevel(mSendLevel);
Andy Hung39399b62017-04-21 15:07:45 -07002156 status_t status = mTrack->start();
2157 if (status == NO_ERROR) {
2158 mVolumeHandler->setStarted();
2159 }
2160 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002161 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002162 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002163}
2164
Marco Nelissen6b74d672012-02-28 16:07:44 -08002165void MediaPlayerService::AudioOutput::setNextOutput(const sp<AudioOutput>& nextOutput) {
Andy Hungd1c74342015-07-07 16:54:23 -07002166 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08002167 mNextOutput = nextOutput;
2168}
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08002169
Marco Nelissen6b74d672012-02-28 16:07:44 -08002170void MediaPlayerService::AudioOutput::switchToNextOutput() {
2171 ALOGV("switchToNextOutput");
Andy Hungd1c74342015-07-07 16:54:23 -07002172
2173 // Try to acquire the callback lock before moving track (without incurring deadlock).
2174 const unsigned kMaxSwitchTries = 100;
2175 Mutex::Autolock lock(mLock);
2176 for (unsigned tries = 0;;) {
2177 if (mTrack == 0) {
2178 return;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002179 }
Andy Hungd1c74342015-07-07 16:54:23 -07002180 if (mNextOutput != NULL && mNextOutput != this) {
2181 if (mCallbackData != NULL) {
2182 // two alternative approaches
2183#if 1
2184 CallbackData *callbackData = mCallbackData;
2185 mLock.unlock();
2186 // proper acquisition sequence
2187 callbackData->lock();
2188 mLock.lock();
2189 // Caution: it is unlikely that someone deleted our callback or changed our target
2190 if (callbackData != mCallbackData || mNextOutput == NULL || mNextOutput == this) {
2191 // fatal if we are starved out.
2192 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
2193 "switchToNextOutput() cannot obtain correct lock sequence");
2194 callbackData->unlock();
2195 continue;
2196 }
2197 callbackData->mSwitching = true; // begin track switch
Wei Jiaadee56a2016-08-05 15:40:34 -07002198 callbackData->setOutput(NULL);
Andy Hungd1c74342015-07-07 16:54:23 -07002199#else
2200 // tryBeginTrackSwitch() returns false if the callback has the lock.
2201 if (!mCallbackData->tryBeginTrackSwitch()) {
2202 // fatal if we are starved out.
2203 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
2204 "switchToNextOutput() cannot obtain callback lock");
2205 mLock.unlock();
2206 usleep(5 * 1000 /* usec */); // allow callback to use AudioOutput
2207 mLock.lock();
2208 continue;
2209 }
2210#endif
2211 }
2212
2213 Mutex::Autolock nextLock(mNextOutput->mLock);
2214
2215 // If the next output track is not NULL, then it has been
2216 // opened already for playback.
2217 // This is possible even without the next player being started,
2218 // for example, the next player could be prepared and seeked.
2219 //
2220 // Presuming it isn't advisable to force the track over.
2221 if (mNextOutput->mTrack == NULL) {
2222 ALOGD("Recycling track for gapless playback");
2223 delete mNextOutput->mCallbackData;
2224 mNextOutput->mCallbackData = mCallbackData;
2225 mNextOutput->mRecycledTrack = mTrack;
2226 mNextOutput->mSampleRateHz = mSampleRateHz;
2227 mNextOutput->mMsecsPerFrame = mMsecsPerFrame;
Andy Hungd1c74342015-07-07 16:54:23 -07002228 mNextOutput->mFlags = mFlags;
2229 mNextOutput->mFrameSize = mFrameSize;
2230 close_l();
2231 mCallbackData = NULL; // destruction handled by mNextOutput
2232 } else {
2233 ALOGW("Ignoring gapless playback because next player has already started");
2234 // remove track in case resource needed for future players.
2235 if (mCallbackData != NULL) {
2236 mCallbackData->endTrackSwitch(); // release lock for callbacks before close.
2237 }
2238 close_l();
2239 }
2240 }
2241 break;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002242 }
2243}
2244
Wei Jia7d3f4df2015-03-03 15:28:00 -08002245ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002246{
Andy Hungd1c74342015-07-07 16:54:23 -07002247 Mutex::Autolock lock(mLock);
Glenn Kastenadad3d72014-02-21 14:51:43 -08002248 LOG_ALWAYS_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
Andreas Huber20111aa2009-07-14 16:56:47 -07002249
Steve Block3856b092011-10-20 11:56:00 +01002250 //ALOGV("write(%p, %u)", buffer, size);
Glenn Kasten2799d742013-05-30 14:33:29 -07002251 if (mTrack != 0) {
Andy Hung2f6e73d2016-04-08 12:12:58 -07002252 return mTrack->write(buffer, size, blocking);
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07002253 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002254 return NO_INIT;
2255}
2256
2257void MediaPlayerService::AudioOutput::stop()
2258{
Steve Block3856b092011-10-20 11:56:00 +01002259 ALOGV("stop");
Andy Hungd1c74342015-07-07 16:54:23 -07002260 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002261 if (mTrack != 0) mTrack->stop();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002262}
2263
2264void MediaPlayerService::AudioOutput::flush()
2265{
Steve Block3856b092011-10-20 11:56:00 +01002266 ALOGV("flush");
Andy Hungd1c74342015-07-07 16:54:23 -07002267 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002268 if (mTrack != 0) mTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002269}
2270
2271void MediaPlayerService::AudioOutput::pause()
2272{
Steve Block3856b092011-10-20 11:56:00 +01002273 ALOGV("pause");
Andy Hungd1c74342015-07-07 16:54:23 -07002274 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002275 if (mTrack != 0) mTrack->pause();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002276}
2277
2278void MediaPlayerService::AudioOutput::close()
2279{
Steve Block3856b092011-10-20 11:56:00 +01002280 ALOGV("close");
Erik Wolsheimer7845a1f2015-10-30 12:07:52 -07002281 sp<AudioTrack> track;
2282 {
2283 Mutex::Autolock lock(mLock);
2284 track = mTrack;
2285 close_l(); // clears mTrack
2286 }
2287 // destruction of the track occurs outside of mutex.
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002288}
2289
2290void MediaPlayerService::AudioOutput::setVolume(float left, float right)
2291{
Steve Block3856b092011-10-20 11:56:00 +01002292 ALOGV("setVolume(%f, %f)", left, right);
Andy Hungd1c74342015-07-07 16:54:23 -07002293 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002294 mLeftVolume = left;
2295 mRightVolume = right;
Glenn Kasten2799d742013-05-30 14:33:29 -07002296 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002297 mTrack->setVolume(left, right);
2298 }
2299}
2300
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002301status_t MediaPlayerService::AudioOutput::setPlaybackRate(const AudioPlaybackRate &rate)
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002302{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002303 ALOGV("setPlaybackRate(%f %f %d %d)",
2304 rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Andy Hungd1c74342015-07-07 16:54:23 -07002305 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002306 if (mTrack == 0) {
2307 // remember rate so that we can set it when the track is opened
2308 mPlaybackRate = rate;
2309 return OK;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002310 }
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002311 status_t res = mTrack->setPlaybackRate(rate);
2312 if (res != NO_ERROR) {
2313 return res;
2314 }
2315 // rate.mSpeed is always greater than 0 if setPlaybackRate succeeded
2316 CHECK_GT(rate.mSpeed, 0.f);
2317 mPlaybackRate = rate;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002318 if (mSampleRateHz != 0) {
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002319 mMsecsPerFrame = 1E3f / (rate.mSpeed * mSampleRateHz);
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002320 }
2321 return res;
2322}
2323
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002324status_t MediaPlayerService::AudioOutput::getPlaybackRate(AudioPlaybackRate *rate)
2325{
2326 ALOGV("setPlaybackRate");
Andy Hungd1c74342015-07-07 16:54:23 -07002327 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002328 if (mTrack == 0) {
2329 return NO_INIT;
2330 }
2331 *rate = mTrack->getPlaybackRate();
2332 return NO_ERROR;
2333}
2334
Eric Laurent2beeb502010-07-16 07:43:46 -07002335status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
2336{
Steve Block3856b092011-10-20 11:56:00 +01002337 ALOGV("setAuxEffectSendLevel(%f)", level);
Andy Hungd1c74342015-07-07 16:54:23 -07002338 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002339 mSendLevel = level;
Glenn Kasten2799d742013-05-30 14:33:29 -07002340 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002341 return mTrack->setAuxEffectSendLevel(level);
2342 }
2343 return NO_ERROR;
2344}
2345
2346status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
2347{
Steve Block3856b092011-10-20 11:56:00 +01002348 ALOGV("attachAuxEffect(%d)", effectId);
Andy Hungd1c74342015-07-07 16:54:23 -07002349 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002350 mAuxEffectId = effectId;
Glenn Kasten2799d742013-05-30 14:33:29 -07002351 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002352 return mTrack->attachAuxEffect(effectId);
2353 }
2354 return NO_ERROR;
2355}
2356
jiabin156c6872017-10-06 09:47:15 -07002357status_t MediaPlayerService::AudioOutput::setOutputDevice(audio_port_handle_t deviceId)
2358{
2359 ALOGV("setOutputDevice(%d)", deviceId);
2360 Mutex::Autolock lock(mLock);
2361 mSelectedDeviceId = deviceId;
2362 if (mTrack != 0) {
2363 return mTrack->setOutputDevice(deviceId);
2364 }
2365 return NO_ERROR;
2366}
2367
2368status_t MediaPlayerService::AudioOutput::getRoutedDeviceId(audio_port_handle_t* deviceId)
2369{
2370 ALOGV("getRoutedDeviceId");
2371 Mutex::Autolock lock(mLock);
2372 if (mTrack != 0) {
jiabin161b64f2017-11-17 09:31:48 -08002373 mRoutedDeviceId = mTrack->getRoutedDeviceId();
jiabin156c6872017-10-06 09:47:15 -07002374 }
jiabin161b64f2017-11-17 09:31:48 -08002375 *deviceId = mRoutedDeviceId;
2376 return NO_ERROR;
jiabin156c6872017-10-06 09:47:15 -07002377}
2378
2379status_t MediaPlayerService::AudioOutput::enableAudioDeviceCallback(bool enabled)
2380{
2381 ALOGV("enableAudioDeviceCallback, %d", enabled);
2382 Mutex::Autolock lock(mLock);
2383 mDeviceCallbackEnabled = enabled;
2384 if (mTrack != 0) {
2385 status_t status;
2386 if (enabled) {
2387 status = mTrack->addAudioDeviceCallback(mDeviceCallback.promote());
2388 } else {
2389 status = mTrack->removeAudioDeviceCallback(mDeviceCallback.promote());
2390 }
2391 return status;
2392 }
2393 return NO_ERROR;
2394}
2395
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002396VolumeShaper::Status MediaPlayerService::AudioOutput::applyVolumeShaper(
2397 const sp<VolumeShaper::Configuration>& configuration,
2398 const sp<VolumeShaper::Operation>& operation)
2399{
2400 Mutex::Autolock lock(mLock);
2401 ALOGV("AudioOutput::applyVolumeShaper");
Andy Hung4ef88d72017-02-21 19:47:53 -08002402
Andy Hung4ef88d72017-02-21 19:47:53 -08002403 mVolumeHandler->setIdIfNecessary(configuration);
Andy Hung39399b62017-04-21 15:07:45 -07002404
2405 VolumeShaper::Status status;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002406 if (mTrack != 0) {
Andy Hung39399b62017-04-21 15:07:45 -07002407 status = mTrack->applyVolumeShaper(configuration, operation);
2408 if (status >= 0) {
2409 (void)mVolumeHandler->applyVolumeShaper(configuration, operation);
Andy Hungf3702642017-05-05 17:33:32 -07002410 if (mTrack->isPlaying()) { // match local AudioTrack to properly restore.
2411 mVolumeHandler->setStarted();
2412 }
Andy Hung39399b62017-04-21 15:07:45 -07002413 }
Andy Hung4ef88d72017-02-21 19:47:53 -08002414 } else {
Andy Hungc01eddb2017-07-21 16:42:41 -07002415 // VolumeShapers are not affected when a track moves between players for
2416 // gapless playback (setNextMediaPlayer).
2417 // We forward VolumeShaper operations that do not change configuration
2418 // to the new player so that unducking may occur as expected.
2419 // Unducking is an idempotent operation, same if applied back-to-back.
2420 if (configuration->getType() == VolumeShaper::Configuration::TYPE_ID
2421 && mNextOutput != nullptr) {
2422 ALOGV("applyVolumeShaper: Attempting to forward missed operation: %s %s",
2423 configuration->toString().c_str(), operation->toString().c_str());
2424 Mutex::Autolock nextLock(mNextOutput->mLock);
2425
2426 // recycled track should be forwarded from this AudioSink by switchToNextOutput
2427 sp<AudioTrack> track = mNextOutput->mRecycledTrack;
2428 if (track != nullptr) {
2429 ALOGD("Forward VolumeShaper operation to recycled track %p", track.get());
2430 (void)track->applyVolumeShaper(configuration, operation);
2431 } else {
2432 // There is a small chance that the unduck occurs after the next
2433 // player has already started, but before it is registered to receive
2434 // the unduck command.
2435 track = mNextOutput->mTrack;
2436 if (track != nullptr) {
2437 ALOGD("Forward VolumeShaper operation to track %p", track.get());
2438 (void)track->applyVolumeShaper(configuration, operation);
2439 }
2440 }
2441 }
Andy Hung39399b62017-04-21 15:07:45 -07002442 status = mVolumeHandler->applyVolumeShaper(configuration, operation);
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002443 }
Andy Hung39399b62017-04-21 15:07:45 -07002444 return status;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002445}
2446
2447sp<VolumeShaper::State> MediaPlayerService::AudioOutput::getVolumeShaperState(int id)
2448{
2449 Mutex::Autolock lock(mLock);
2450 if (mTrack != 0) {
2451 return mTrack->getVolumeShaperState(id);
Andy Hung4ef88d72017-02-21 19:47:53 -08002452 } else {
2453 return mVolumeHandler->getVolumeShaperState(id);
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002454 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002455}
2456
Andreas Huber20111aa2009-07-14 16:56:47 -07002457// static
2458void MediaPlayerService::AudioOutput::CallbackWrapper(
Glenn Kastend217a8c2011-06-01 15:20:35 -07002459 int event, void *cookie, void *info) {
Steve Block3856b092011-10-20 11:56:00 +01002460 //ALOGV("callbackwrapper");
Marco Nelissen6b74d672012-02-28 16:07:44 -08002461 CallbackData *data = (CallbackData*)cookie;
Andy Hungd1c74342015-07-07 16:54:23 -07002462 // lock to ensure we aren't caught in the middle of a track switch.
Marco Nelissen6b74d672012-02-28 16:07:44 -08002463 data->lock();
2464 AudioOutput *me = data->getOutput();
Andreas Huber20111aa2009-07-14 16:56:47 -07002465 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002466 if (me == NULL) {
2467 // no output set, likely because the track was scheduled to be reused
2468 // by another player, but the format turned out to be incompatible.
2469 data->unlock();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002470 if (buffer != NULL) {
2471 buffer->size = 0;
2472 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08002473 return;
2474 }
Andreas Huber20111aa2009-07-14 16:56:47 -07002475
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002476 switch(event) {
2477 case AudioTrack::EVENT_MORE_DATA: {
2478 size_t actualSize = (*me->mCallback)(
2479 me, buffer->raw, buffer->size, me->mCallbackCookie,
2480 CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002481
Andy Hung719b46b2015-05-31 22:18:25 -07002482 // Log when no data is returned from the callback.
2483 // (1) We may have no data (especially with network streaming sources).
2484 // (2) We may have reached the EOS and the audio track is not stopped yet.
2485 // Note that AwesomePlayer/AudioPlayer will only return zero size when it reaches the EOS.
2486 // NuPlayerRenderer will return zero when it doesn't have data (it doesn't block to fill).
2487 //
2488 // This is a benign busy-wait, with the next data request generated 10 ms or more later;
2489 // nevertheless for power reasons, we don't want to see too many of these.
Andreas Huber2e8ffaf2010-02-18 16:45:13 -08002490
Andy Hung719b46b2015-05-31 22:18:25 -07002491 ALOGV_IF(actualSize == 0 && buffer->size > 0, "callbackwrapper: empty buffer returned");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002492
2493 buffer->size = actualSize;
2494 } break;
2495
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002496 case AudioTrack::EVENT_STREAM_END:
Andy Hung719b46b2015-05-31 22:18:25 -07002497 // currently only occurs for offloaded callbacks
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002498 ALOGV("callbackwrapper: deliver EVENT_STREAM_END");
2499 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2500 me->mCallbackCookie, CB_EVENT_STREAM_END);
2501 break;
2502
2503 case AudioTrack::EVENT_NEW_IAUDIOTRACK :
2504 ALOGV("callbackwrapper: deliver EVENT_TEAR_DOWN");
2505 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2506 me->mCallbackCookie, CB_EVENT_TEAR_DOWN);
2507 break;
2508
Glenn Kasten421743b2015-06-01 08:18:08 -07002509 case AudioTrack::EVENT_UNDERRUN:
Andy Hung719b46b2015-05-31 22:18:25 -07002510 // This occurs when there is no data available, typically
Glenn Kasten421743b2015-06-01 08:18:08 -07002511 // when there is a failure to supply data to the AudioTrack. It can also
2512 // occur in non-offloaded mode when the audio device comes out of standby.
2513 //
Andy Hung719b46b2015-05-31 22:18:25 -07002514 // If an AudioTrack underruns it outputs silence. Since this happens suddenly
2515 // it may sound like an audible pop or glitch.
2516 //
2517 // The underrun event is sent once per track underrun; the condition is reset
2518 // when more data is sent to the AudioTrack.
Eric Laurente93cc032016-05-05 10:15:10 -07002519 ALOGD("callbackwrapper: EVENT_UNDERRUN (discarded)");
Glenn Kasten421743b2015-06-01 08:18:08 -07002520 break;
2521
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002522 default:
2523 ALOGE("received unknown event type: %d inside CallbackWrapper !", event);
Andreas Huber51c1e0e2011-04-04 11:43:40 -07002524 }
2525
Marco Nelissen6b74d672012-02-28 16:07:44 -08002526 data->unlock();
Andreas Huber20111aa2009-07-14 16:56:47 -07002527}
2528
Glenn Kastend848eb42016-03-08 13:42:11 -08002529audio_session_t MediaPlayerService::AudioOutput::getSessionId() const
Eric Laurent8c563ed2010-10-07 18:23:03 -07002530{
Andy Hungd1c74342015-07-07 16:54:23 -07002531 Mutex::Autolock lock(mLock);
Eric Laurent8c563ed2010-10-07 18:23:03 -07002532 return mSessionId;
2533}
2534
Eric Laurent6f59db12013-07-26 17:16:50 -07002535uint32_t MediaPlayerService::AudioOutput::getSampleRate() const
2536{
Andy Hungd1c74342015-07-07 16:54:23 -07002537 Mutex::Autolock lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -07002538 if (mTrack == 0) return 0;
2539 return mTrack->getSampleRate();
2540}
2541
Andy Hungf2c87b32016-04-07 19:49:29 -07002542int64_t MediaPlayerService::AudioOutput::getBufferDurationInUs() const
2543{
2544 Mutex::Autolock lock(mLock);
2545 if (mTrack == 0) {
2546 return 0;
2547 }
2548 int64_t duration;
2549 if (mTrack->getBufferDurationInUs(&duration) != OK) {
2550 return 0;
2551 }
2552 return duration;
2553}
2554
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002555////////////////////////////////////////////////////////////////////////////////
2556
2557struct CallbackThread : public Thread {
2558 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
2559 MediaPlayerBase::AudioSink::AudioCallback cb,
2560 void *cookie);
2561
2562protected:
2563 virtual ~CallbackThread();
2564
2565 virtual bool threadLoop();
2566
2567private:
2568 wp<MediaPlayerBase::AudioSink> mSink;
2569 MediaPlayerBase::AudioSink::AudioCallback mCallback;
2570 void *mCookie;
2571 void *mBuffer;
2572 size_t mBufferSize;
2573
2574 CallbackThread(const CallbackThread &);
2575 CallbackThread &operator=(const CallbackThread &);
2576};
2577
2578CallbackThread::CallbackThread(
2579 const wp<MediaPlayerBase::AudioSink> &sink,
2580 MediaPlayerBase::AudioSink::AudioCallback cb,
2581 void *cookie)
2582 : mSink(sink),
2583 mCallback(cb),
2584 mCookie(cookie),
2585 mBuffer(NULL),
2586 mBufferSize(0) {
2587}
2588
2589CallbackThread::~CallbackThread() {
2590 if (mBuffer) {
2591 free(mBuffer);
2592 mBuffer = NULL;
2593 }
2594}
2595
2596bool CallbackThread::threadLoop() {
2597 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
2598 if (sink == NULL) {
2599 return false;
2600 }
2601
2602 if (mBuffer == NULL) {
2603 mBufferSize = sink->bufferSize();
2604 mBuffer = malloc(mBufferSize);
2605 }
2606
2607 size_t actualSize =
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002608 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie,
2609 MediaPlayerBase::AudioSink::CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002610
2611 if (actualSize > 0) {
2612 sink->write(mBuffer, actualSize);
Andy Hunga31335a2014-08-20 17:37:59 -07002613 // Could return false on sink->write() error or short count.
2614 // Not necessarily appropriate but would work for AudioCache behavior.
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002615 }
2616
2617 return true;
2618}
2619
2620////////////////////////////////////////////////////////////////////////////////
2621
Chong Zhange5b9b692017-05-11 11:44:56 -07002622void MediaPlayerService::addBatteryData(uint32_t params) {
2623 mBatteryTracker.addBatteryData(params);
2624}
2625
2626status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
2627 return mBatteryTracker.pullBatteryData(reply);
2628}
2629
2630MediaPlayerService::BatteryTracker::BatteryTracker() {
2631 mBatteryAudio.refCount = 0;
2632 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2633 mBatteryAudio.deviceOn[i] = 0;
2634 mBatteryAudio.lastTime[i] = 0;
2635 mBatteryAudio.totalTime[i] = 0;
2636 }
2637 // speaker is on by default
2638 mBatteryAudio.deviceOn[SPEAKER] = 1;
2639
2640 // reset battery stats
2641 // if the mediaserver has crashed, battery stats could be left
2642 // in bad state, reset the state upon service start.
2643 BatteryNotifier::getInstance().noteResetVideo();
2644}
2645
2646void MediaPlayerService::BatteryTracker::addBatteryData(uint32_t params)
Gloria Wang7cf180c2011-02-19 18:37:57 -08002647{
2648 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002649
2650 int32_t time = systemTime() / 1000000L;
2651
2652 // change audio output devices. This notification comes from AudioFlinger
2653 if ((params & kBatteryDataSpeakerOn)
2654 || (params & kBatteryDataOtherAudioDeviceOn)) {
2655
2656 int deviceOn[NUM_AUDIO_DEVICES];
2657 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2658 deviceOn[i] = 0;
2659 }
2660
2661 if ((params & kBatteryDataSpeakerOn)
2662 && (params & kBatteryDataOtherAudioDeviceOn)) {
2663 deviceOn[SPEAKER_AND_OTHER] = 1;
2664 } else if (params & kBatteryDataSpeakerOn) {
2665 deviceOn[SPEAKER] = 1;
2666 } else {
2667 deviceOn[OTHER_AUDIO_DEVICE] = 1;
2668 }
2669
2670 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2671 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
2672
2673 if (mBatteryAudio.refCount > 0) { // if playing audio
2674 if (!deviceOn[i]) {
2675 mBatteryAudio.lastTime[i] += time;
2676 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2677 mBatteryAudio.lastTime[i] = 0;
2678 } else {
2679 mBatteryAudio.lastTime[i] = 0 - time;
2680 }
2681 }
2682
2683 mBatteryAudio.deviceOn[i] = deviceOn[i];
2684 }
2685 }
2686 return;
2687 }
2688
Marco Nelissenb7848f12014-12-04 08:57:56 -08002689 // an audio stream is started
Gloria Wang9ee159b2011-02-24 14:51:45 -08002690 if (params & kBatteryDataAudioFlingerStart) {
2691 // record the start time only if currently no other audio
2692 // is being played
2693 if (mBatteryAudio.refCount == 0) {
2694 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2695 if (mBatteryAudio.deviceOn[i]) {
2696 mBatteryAudio.lastTime[i] -= time;
2697 }
2698 }
2699 }
2700
2701 mBatteryAudio.refCount ++;
2702 return;
2703
2704 } else if (params & kBatteryDataAudioFlingerStop) {
2705 if (mBatteryAudio.refCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002706 ALOGW("Battery track warning: refCount is <= 0");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002707 return;
2708 }
2709
2710 // record the stop time only if currently this is the only
2711 // audio being played
2712 if (mBatteryAudio.refCount == 1) {
2713 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2714 if (mBatteryAudio.deviceOn[i]) {
2715 mBatteryAudio.lastTime[i] += time;
2716 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2717 mBatteryAudio.lastTime[i] = 0;
2718 }
2719 }
2720 }
2721
2722 mBatteryAudio.refCount --;
2723 return;
2724 }
2725
Andy Hung1afd0982016-11-08 16:13:44 -08002726 uid_t uid = IPCThreadState::self()->getCallingUid();
Gloria Wang7cf180c2011-02-19 18:37:57 -08002727 if (uid == AID_MEDIA) {
2728 return;
2729 }
2730 int index = mBatteryData.indexOfKey(uid);
Gloria Wang7cf180c2011-02-19 18:37:57 -08002731
2732 if (index < 0) { // create a new entry for this UID
2733 BatteryUsageInfo info;
2734 info.audioTotalTime = 0;
2735 info.videoTotalTime = 0;
2736 info.audioLastTime = 0;
2737 info.videoLastTime = 0;
2738 info.refCount = 0;
2739
Gloria Wang9ee159b2011-02-24 14:51:45 -08002740 if (mBatteryData.add(uid, info) == NO_MEMORY) {
Steve Block29357bc2012-01-06 19:20:56 +00002741 ALOGE("Battery track error: no memory for new app");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002742 return;
2743 }
Gloria Wang7cf180c2011-02-19 18:37:57 -08002744 }
2745
2746 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
2747
2748 if (params & kBatteryDataCodecStarted) {
2749 if (params & kBatteryDataTrackAudio) {
2750 info.audioLastTime -= time;
2751 info.refCount ++;
2752 }
2753 if (params & kBatteryDataTrackVideo) {
2754 info.videoLastTime -= time;
2755 info.refCount ++;
2756 }
2757 } else {
2758 if (info.refCount == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002759 ALOGW("Battery track warning: refCount is already 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002760 return;
2761 } else if (info.refCount < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00002762 ALOGE("Battery track error: refCount < 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002763 mBatteryData.removeItem(uid);
2764 return;
2765 }
2766
2767 if (params & kBatteryDataTrackAudio) {
2768 info.audioLastTime += time;
2769 info.refCount --;
2770 }
2771 if (params & kBatteryDataTrackVideo) {
2772 info.videoLastTime += time;
2773 info.refCount --;
2774 }
2775
2776 // no stream is being played by this UID
2777 if (info.refCount == 0) {
2778 info.audioTotalTime += info.audioLastTime;
2779 info.audioLastTime = 0;
2780 info.videoTotalTime += info.videoLastTime;
2781 info.videoLastTime = 0;
2782 }
2783 }
2784}
2785
Chong Zhange5b9b692017-05-11 11:44:56 -07002786status_t MediaPlayerService::BatteryTracker::pullBatteryData(Parcel* reply) {
Gloria Wang7cf180c2011-02-19 18:37:57 -08002787 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002788
2789 // audio output devices usage
2790 int32_t time = systemTime() / 1000000L; //in ms
2791 int32_t totalTime;
2792
2793 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2794 totalTime = mBatteryAudio.totalTime[i];
2795
2796 if (mBatteryAudio.deviceOn[i]
2797 && (mBatteryAudio.lastTime[i] != 0)) {
2798 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
2799 totalTime += tmpTime;
2800 }
2801
2802 reply->writeInt32(totalTime);
2803 // reset the total time
2804 mBatteryAudio.totalTime[i] = 0;
2805 }
2806
2807 // codec usage
Gloria Wang7cf180c2011-02-19 18:37:57 -08002808 BatteryUsageInfo info;
2809 int size = mBatteryData.size();
2810
2811 reply->writeInt32(size);
2812 int i = 0;
2813
2814 while (i < size) {
2815 info = mBatteryData.valueAt(i);
2816
2817 reply->writeInt32(mBatteryData.keyAt(i)); //UID
2818 reply->writeInt32(info.audioTotalTime);
2819 reply->writeInt32(info.videoTotalTime);
2820
2821 info.audioTotalTime = 0;
2822 info.videoTotalTime = 0;
2823
2824 // remove the UID entry where no stream is being played
2825 if (info.refCount <= 0) {
2826 mBatteryData.removeItemsAt(i);
2827 size --;
2828 i --;
2829 }
2830 i++;
2831 }
2832 return NO_ERROR;
2833}
nikoa64c8c72009-07-20 15:07:26 -07002834} // namespace android