blob: 46c130fca8784063f459d247f56516a2421ce411 [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
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -070037#include <android/hardware/media/omx/1.0/IOmx.h>
Marco Nelissena0c98412019-03-29 12:10:19 -070038#include <android/hardware/media/c2/1.0/IComponentStore.h>
Mathias Agopian75624082009-05-19 19:08:10 -070039#include <binder/IPCThreadState.h>
40#include <binder/IServiceManager.h>
41#include <binder/MemoryHeapBase.h>
42#include <binder/MemoryBase.h>
Mathias Agopianb1e7cd12013-02-14 17:11:27 -080043#include <gui/Surface.h>
Nicolas Catania1d187f12009-05-12 23:25:55 -070044#include <utils/Errors.h> // for status_t
45#include <utils/String8.h>
Marco Nelissen10dbb8e2009-09-20 10:42:13 -070046#include <utils/SystemClock.h>
Lajos Molnar06ad1522014-08-28 07:27:44 -070047#include <utils/Timers.h>
Nicolas Catania1d187f12009-05-12 23:25:55 -070048#include <utils/Vector.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080049
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -070050#include <codec2/hidl/client.h>
Marco Nelissenfa8be7d2019-09-23 12:15:57 -070051#include <datasource/HTTPBase.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080052#include <media/IMediaHTTPService.h>
Jeff Brown2013a542012-09-04 21:38:42 -070053#include <media/IRemoteDisplay.h>
54#include <media/IRemoteDisplayClient.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080055#include <media/MediaPlayerInterface.h>
56#include <media/mediarecorder.h>
57#include <media/MediaMetadataRetrieverInterface.h>
nikoa64c8c72009-07-20 15:07:26 -070058#include <media/Metadata.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080059#include <media/AudioTrack.h>
James Dong8635b7b2011-03-14 17:01:38 -070060#include <media/MemoryLeakTrackUtil.h>
Dongwon Kangd91dc5a2017-10-10 00:07:09 -070061#include <media/stagefright/InterfaceUtils.h>
Lajos Molnar1381d4b2014-08-07 15:18:35 -070062#include <media/stagefright/MediaCodecList.h>
Eric Laurent9cb839a2011-09-27 09:48:56 -070063#include <media/stagefright/MediaErrors.h>
Marco Nelissen83b0fd92015-09-16 13:48:07 -070064#include <media/stagefright/Utils.h>
Marco Nelissenfa8be7d2019-09-23 12:15:57 -070065#include <media/stagefright/FoundationUtils.h>
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +010066#include <media/stagefright/foundation/ADebug.h>
Marco Nelissenf09611f2015-02-13 14:12:42 -080067#include <media/stagefright/foundation/ALooperRoster.h>
Chong Zhang181fd9b2017-02-16 15:53:03 -080068#include <media/stagefright/SurfaceUtils.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070069#include <mediautils/BatteryNotifier.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080070
Andy Hung53541292016-04-13 16:48:51 -070071#include <memunreachable/memunreachable.h>
Dima Zavin64760242011-05-11 14:15:23 -070072#include <system/audio.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070073
Gloria Wang7cf180c2011-02-19 18:37:57 -080074#include <private/android_filesystem_config.h>
75
James Dong559bf282012-03-28 10:29:14 -070076#include "ActivityManager.h"
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080077#include "MediaRecorderClient.h"
78#include "MediaPlayerService.h"
79#include "MetadataRetrieverClient.h"
John Grossman44a7e422012-06-21 17:29:24 -070080#include "MediaPlayerFactory.h"
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080081
Nicolas Catania14d27472009-07-13 14:37:49 -070082#include "TestPlayerStub.h"
Andreas Huberf9334412010-12-15 15:17:42 -080083#include "nuplayer/NuPlayerDriver.h"
Andreas Huber20111aa2009-07-14 16:56:47 -070084
Andreas Hubered3e3e02012-03-26 11:13:27 -070085
Wei Jia502c2f42017-07-13 17:47:56 -070086static const int kDumpLockRetries = 50;
87static const int kDumpLockSleepUs = 20000;
88
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070089namespace {
nikoa64c8c72009-07-20 15:07:26 -070090using android::media::Metadata;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070091using android::status_t;
92using android::OK;
93using android::BAD_VALUE;
94using android::NOT_ENOUGH_DATA;
95using android::Parcel;
Ivan Lozano8cf3a072017-08-09 09:01:33 -070096using android::media::VolumeShaper;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070097
98// Max number of entries in the filter.
99const int kMaxFilterSize = 64; // I pulled that out of thin air.
100
Andy Hungff874dc2016-04-11 16:49:09 -0700101const float kMaxRequiredSpeed = 8.0f; // for PCM tracks allow up to 8x speedup.
102
nikoa64c8c72009-07-20 15:07:26 -0700103// FIXME: Move all the metadata related function in the Metadata.cpp
nikod608a812009-07-16 16:39:53 -0700104
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700105
106// Unmarshall a filter from a Parcel.
107// Filter format in a parcel:
108//
109// 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
110// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
111// | number of entries (n) |
112// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
113// | metadata type 1 |
114// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
115// | metadata type 2 |
116// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
117// ....
118// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
119// | metadata type n |
120// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
121//
122// @param p Parcel that should start with a filter.
123// @param[out] filter On exit contains the list of metadata type to be
124// filtered.
125// @param[out] status On exit contains the status code to be returned.
126// @return true if the parcel starts with a valid filter.
127bool unmarshallFilter(const Parcel& p,
nikoa64c8c72009-07-20 15:07:26 -0700128 Metadata::Filter *filter,
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700129 status_t *status)
130{
Nicolas Catania48290382009-07-10 13:53:06 -0700131 int32_t val;
132 if (p.readInt32(&val) != OK)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700133 {
Steve Block29357bc2012-01-06 19:20:56 +0000134 ALOGE("Failed to read filter's length");
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700135 *status = NOT_ENOUGH_DATA;
136 return false;
137 }
138
Nicolas Catania48290382009-07-10 13:53:06 -0700139 if( val > kMaxFilterSize || val < 0)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700140 {
Steve Block29357bc2012-01-06 19:20:56 +0000141 ALOGE("Invalid filter len %d", val);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700142 *status = BAD_VALUE;
143 return false;
144 }
145
Nicolas Catania48290382009-07-10 13:53:06 -0700146 const size_t num = val;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700147
148 filter->clear();
Nicolas Catania48290382009-07-10 13:53:06 -0700149 filter->setCapacity(num);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700150
nikoa64c8c72009-07-20 15:07:26 -0700151 size_t size = num * sizeof(Metadata::Type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700152
Nicolas Catania48290382009-07-10 13:53:06 -0700153
154 if (p.dataAvail() < size)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700155 {
Andy Hung833b4752016-04-04 17:15:48 -0700156 ALOGE("Filter too short expected %zu but got %zu", size, p.dataAvail());
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700157 *status = NOT_ENOUGH_DATA;
158 return false;
159 }
160
nikoa64c8c72009-07-20 15:07:26 -0700161 const Metadata::Type *data =
162 static_cast<const Metadata::Type*>(p.readInplace(size));
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700163
Nicolas Catania48290382009-07-10 13:53:06 -0700164 if (NULL == data)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700165 {
Steve Block29357bc2012-01-06 19:20:56 +0000166 ALOGE("Filter had no data");
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700167 *status = BAD_VALUE;
168 return false;
169 }
170
171 // TODO: The stl impl of vector would be more efficient here
172 // because it degenerates into a memcpy on pod types. Try to
173 // replace later or use stl::set.
Nicolas Catania48290382009-07-10 13:53:06 -0700174 for (size_t i = 0; i < num; ++i)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700175 {
Nicolas Catania48290382009-07-10 13:53:06 -0700176 filter->add(*data);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700177 ++data;
178 }
179 *status = OK;
180 return true;
181}
182
Nicolas Catania48290382009-07-10 13:53:06 -0700183// @param filter Of metadata type.
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700184// @param val To be searched.
185// @return true if a match was found.
nikoa64c8c72009-07-20 15:07:26 -0700186bool findMetadata(const Metadata::Filter& filter, const int32_t val)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700187{
188 // Deal with empty and ANY right away
189 if (filter.isEmpty()) return false;
nikoa64c8c72009-07-20 15:07:26 -0700190 if (filter[0] == Metadata::kAny) return true;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700191
Nicolas Catania48290382009-07-10 13:53:06 -0700192 return filter.indexOf(val) >= 0;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700193}
194
195} // anonymous namespace
196
197
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700198namespace {
199using android::Parcel;
200using android::String16;
201
202// marshalling tag indicating flattened utf16 tags
203// keep in sync with frameworks/base/media/java/android/media/AudioAttributes.java
204const int32_t kAudioAttributesMarshallTagFlattenTags = 1;
205
206// Audio attributes format in a parcel:
207//
208// 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
209// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
210// | usage |
211// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
212// | content_type |
213// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Hyejin Kim4f418f92014-09-05 15:50:03 +0900214// | source |
215// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700216// | flags |
217// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
218// | kAudioAttributesMarshallTagFlattenTags | // ignore tags if not found
219// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
220// | flattened tags in UTF16 |
221// | ... |
222// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
223//
224// @param p Parcel that contains audio attributes.
225// @param[out] attributes On exit points to an initialized audio_attributes_t structure
226// @param[out] status On exit contains the status code to be returned.
227void unmarshallAudioAttributes(const Parcel& parcel, audio_attributes_t *attributes)
228{
229 attributes->usage = (audio_usage_t) parcel.readInt32();
230 attributes->content_type = (audio_content_type_t) parcel.readInt32();
Hyejin Kim4f418f92014-09-05 15:50:03 +0900231 attributes->source = (audio_source_t) parcel.readInt32();
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700232 attributes->flags = (audio_flags_mask_t) parcel.readInt32();
233 const bool hasFlattenedTag = (parcel.readInt32() == kAudioAttributesMarshallTagFlattenTags);
234 if (hasFlattenedTag) {
235 // the tags are UTF16, convert to UTF8
236 String16 tags = parcel.readString16();
237 ssize_t realTagSize = utf16_to_utf8_length(tags.string(), tags.size());
238 if (realTagSize <= 0) {
239 strcpy(attributes->tags, "");
240 } else {
241 // copy the flattened string into the attributes as the destination for the conversion:
242 // copying array size -1, array for tags was calloc'd, no need to NULL-terminate it
243 size_t tagSize = realTagSize > AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 ?
244 AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 : realTagSize;
Sergio Giro1d3f4272016-06-28 18:24:52 +0100245 utf16_to_utf8(tags.string(), tagSize, attributes->tags,
246 sizeof(attributes->tags) / sizeof(attributes->tags[0]));
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700247 }
248 } else {
249 ALOGE("unmarshallAudioAttributes() received unflattened tags, ignoring tag values");
250 strcpy(attributes->tags, "");
251 }
252}
253} // anonymous namespace
254
255
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800256namespace android {
257
Marco Nelissenf09611f2015-02-13 14:12:42 -0800258extern ALooperRoster gLooperRoster;
259
260
Dave Burked681bbb2011-08-30 14:39:17 +0100261static bool checkPermission(const char* permissionString) {
Dave Burked681bbb2011-08-30 14:39:17 +0100262 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
263 bool ok = checkCallingPermission(String16(permissionString));
Steve Block29357bc2012-01-06 19:20:56 +0000264 if (!ok) ALOGE("Request requires %s", permissionString);
Dave Burked681bbb2011-08-30 14:39:17 +0100265 return ok;
266}
267
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800268// 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 -0800269/* static */ int MediaPlayerService::AudioOutput::mMinBufferCount = 4;
270/* static */ bool MediaPlayerService::AudioOutput::mIsOnEmulator = false;
271
272void MediaPlayerService::instantiate() {
273 defaultServiceManager()->addService(
274 String16("media.player"), new MediaPlayerService());
275}
276
277MediaPlayerService::MediaPlayerService()
278{
Steve Block3856b092011-10-20 11:56:00 +0100279 ALOGV("MediaPlayerService created");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800280 mNextConnId = 1;
Gloria Wang9ee159b2011-02-24 14:51:45 -0800281
John Grossman44a7e422012-06-21 17:29:24 -0700282 MediaPlayerFactory::registerBuiltinFactories();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800283}
284
285MediaPlayerService::~MediaPlayerService()
286{
Steve Block3856b092011-10-20 11:56:00 +0100287 ALOGV("MediaPlayerService destroyed");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800288}
289
Svet Ganovbe71aa22015-04-28 12:06:02 -0700290sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(const String16 &opPackageName)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800291{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800292 pid_t pid = IPCThreadState::self()->getCallingPid();
Svet Ganovbe71aa22015-04-28 12:06:02 -0700293 sp<MediaRecorderClient> recorder = new MediaRecorderClient(this, pid, opPackageName);
Gloria Wangdac6a312009-10-29 15:46:37 -0700294 wp<MediaRecorderClient> w = recorder;
295 Mutex::Autolock lock(mLock);
296 mMediaRecorderClients.add(w);
Steve Block3856b092011-10-20 11:56:00 +0100297 ALOGV("Create new media recorder client from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800298 return recorder;
299}
300
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -0700301void MediaPlayerService::removeMediaRecorderClient(const wp<MediaRecorderClient>& client)
Gloria Wangdac6a312009-10-29 15:46:37 -0700302{
303 Mutex::Autolock lock(mLock);
304 mMediaRecorderClients.remove(client);
Steve Block3856b092011-10-20 11:56:00 +0100305 ALOGV("Delete media recorder client");
Gloria Wangdac6a312009-10-29 15:46:37 -0700306}
307
Glenn Kastenf37971f2012-02-03 11:06:53 -0800308sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800309{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800310 pid_t pid = IPCThreadState::self()->getCallingPid();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800311 sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
Steve Block3856b092011-10-20 11:56:00 +0100312 ALOGV("Create new media retriever from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800313 return retriever;
314}
315
Glenn Kastenf37971f2012-02-03 11:06:53 -0800316sp<IMediaPlayer> MediaPlayerService::create(const sp<IMediaPlayerClient>& client,
Glenn Kastend848eb42016-03-08 13:42:11 -0800317 audio_session_t audioSessionId)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800318{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800319 pid_t pid = IPCThreadState::self()->getCallingPid();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800320 int32_t connId = android_atomic_inc(&mNextConnId);
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700321
322 sp<Client> c = new Client(
323 this, pid, connId, client, audioSessionId,
324 IPCThreadState::self()->getCallingUid());
325
Steve Block3856b092011-10-20 11:56:00 +0100326 ALOGV("Create new client(%d) from pid %d, uid %d, ", connId, pid,
Dave Burked681bbb2011-08-30 14:39:17 +0100327 IPCThreadState::self()->getCallingUid());
328
329 wp<Client> w = c;
330 {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800331 Mutex::Autolock lock(mLock);
332 mClients.add(w);
333 }
Andreas Hubere2b10282010-11-23 11:41:34 -0800334 return c;
335}
336
Lajos Molnar1381d4b2014-08-07 15:18:35 -0700337sp<IMediaCodecList> MediaPlayerService::getCodecList() const {
338 return MediaCodecList::getLocalInstance();
339}
340
Jeff Brown2013a542012-09-04 21:38:42 -0700341sp<IRemoteDisplay> MediaPlayerService::listenForRemoteDisplay(
Chong Zhangd0a98fa2017-09-14 17:43:10 -0700342 const String16 &/*opPackageName*/,
343 const sp<IRemoteDisplayClient>& /*client*/,
344 const String8& /*iface*/) {
345 ALOGE("listenForRemoteDisplay is no longer supported!");
Jeff Brownaba33d52012-09-07 17:38:58 -0700346
Chong Zhangd0a98fa2017-09-14 17:43:10 -0700347 return NULL;
Jeff Brown2013a542012-09-04 21:38:42 -0700348}
349
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800350status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
351{
352 const size_t SIZE = 256;
353 char buffer[SIZE];
354 String8 result;
355
356 result.append(" AudioOutput\n");
357 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n",
358 mStreamType, mLeftVolume, mRightVolume);
359 result.append(buffer);
360 snprintf(buffer, 255, " msec per frame(%f), latency (%d)\n",
Eric Laurentdb354e52012-03-05 17:27:11 -0800361 mMsecsPerFrame, (mTrack != 0) ? mTrack->latency() : -1);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800362 result.append(buffer);
Eric Laurent2beeb502010-07-16 07:43:46 -0700363 snprintf(buffer, 255, " aux effect id(%d), send level (%f)\n",
364 mAuxEffectId, mSendLevel);
365 result.append(buffer);
366
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800367 ::write(fd, result.string(), result.size());
368 if (mTrack != 0) {
369 mTrack->dump(fd, args);
370 }
371 return NO_ERROR;
372}
373
Lajos Molnar6d339f12015-04-17 16:15:53 -0700374status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800375{
376 const size_t SIZE = 256;
377 char buffer[SIZE];
378 String8 result;
379 result.append(" Client\n");
380 snprintf(buffer, 255, " pid(%d), connId(%d), status(%d), looping(%s)\n",
381 mPid, mConnId, mStatus, mLoop?"true": "false");
382 result.append(buffer);
Wei Jia502c2f42017-07-13 17:47:56 -0700383
384 sp<MediaPlayerBase> p;
385 sp<AudioOutput> audioOutput;
386 bool locked = false;
387 for (int i = 0; i < kDumpLockRetries; ++i) {
388 if (mLock.tryLock() == NO_ERROR) {
389 locked = true;
390 break;
391 }
392 usleep(kDumpLockSleepUs);
Andreas Hubera0b1d4b2011-06-07 15:52:25 -0700393 }
Wei Jia502c2f42017-07-13 17:47:56 -0700394
395 if (locked) {
396 p = mPlayer;
397 audioOutput = mAudioOutput;
398 mLock.unlock();
399 } else {
400 result.append(" lock is taken, no dump from player and audio output\n");
401 }
402 write(fd, result.string(), result.size());
403
404 if (p != NULL) {
405 p->dump(fd, args);
406 }
407 if (audioOutput != 0) {
408 audioOutput->dump(fd, args);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800409 }
410 write(fd, "\n", 1);
411 return NO_ERROR;
412}
413
Marco Nelissenf09611f2015-02-13 14:12:42 -0800414/**
415 * The only arguments this understands right now are -c, -von and -voff,
416 * which are parsed by ALooperRoster::dump()
417 */
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800418status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
419{
420 const size_t SIZE = 256;
421 char buffer[SIZE];
422 String8 result;
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530423 SortedVector< sp<Client> > clients; //to serialise the mutex unlock & client destruction.
424 SortedVector< sp<MediaRecorderClient> > mediaRecorderClients;
425
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800426 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
427 snprintf(buffer, SIZE, "Permission Denial: "
428 "can't dump MediaPlayerService from pid=%d, uid=%d\n",
429 IPCThreadState::self()->getCallingPid(),
430 IPCThreadState::self()->getCallingUid());
431 result.append(buffer);
432 } else {
433 Mutex::Autolock lock(mLock);
434 for (int i = 0, n = mClients.size(); i < n; ++i) {
435 sp<Client> c = mClients[i].promote();
436 if (c != 0) c->dump(fd, args);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530437 clients.add(c);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800438 }
James Dongb9141222010-07-08 11:16:11 -0700439 if (mMediaRecorderClients.size() == 0) {
440 result.append(" No media recorder client\n\n");
441 } else {
442 for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
443 sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
James Donge579e282011-10-18 22:29:20 -0700444 if (c != 0) {
445 snprintf(buffer, 255, " MediaRecorderClient pid(%d)\n", c->mPid);
446 result.append(buffer);
447 write(fd, result.string(), result.size());
448 result = "\n";
449 c->dump(fd, args);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530450 mediaRecorderClients.add(c);
James Donge579e282011-10-18 22:29:20 -0700451 }
James Dongb9141222010-07-08 11:16:11 -0700452 }
Gloria Wangdac6a312009-10-29 15:46:37 -0700453 }
454
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800455 result.append(" Files opened and/or mapped:\n");
Marco Nelissenf09611f2015-02-13 14:12:42 -0800456 snprintf(buffer, SIZE, "/proc/%d/maps", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800457 FILE *f = fopen(buffer, "r");
458 if (f) {
459 while (!feof(f)) {
460 fgets(buffer, SIZE, f);
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700461 if (strstr(buffer, " /storage/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800462 strstr(buffer, " /system/sounds/") ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700463 strstr(buffer, " /data/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800464 strstr(buffer, " /system/media/")) {
465 result.append(" ");
466 result.append(buffer);
467 }
468 }
469 fclose(f);
470 } else {
471 result.append("couldn't open ");
472 result.append(buffer);
473 result.append("\n");
474 }
475
Marco Nelissenf09611f2015-02-13 14:12:42 -0800476 snprintf(buffer, SIZE, "/proc/%d/fd", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800477 DIR *d = opendir(buffer);
478 if (d) {
479 struct dirent *ent;
480 while((ent = readdir(d)) != NULL) {
481 if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
Marco Nelissenf09611f2015-02-13 14:12:42 -0800482 snprintf(buffer, SIZE, "/proc/%d/fd/%s", getpid(), ent->d_name);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800483 struct stat s;
484 if (lstat(buffer, &s) == 0) {
485 if ((s.st_mode & S_IFMT) == S_IFLNK) {
486 char linkto[256];
487 int len = readlink(buffer, linkto, sizeof(linkto));
488 if(len > 0) {
489 if(len > 255) {
490 linkto[252] = '.';
491 linkto[253] = '.';
492 linkto[254] = '.';
493 linkto[255] = 0;
494 } else {
495 linkto[len] = 0;
496 }
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700497 if (strstr(linkto, "/storage/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800498 strstr(linkto, "/system/sounds/") == linkto ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700499 strstr(linkto, "/data/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800500 strstr(linkto, "/system/media/") == linkto) {
501 result.append(" ");
502 result.append(buffer);
503 result.append(" -> ");
504 result.append(linkto);
505 result.append("\n");
506 }
507 }
508 } else {
509 result.append(" unexpected type for ");
510 result.append(buffer);
511 result.append("\n");
512 }
513 }
514 }
515 }
516 closedir(d);
517 } else {
518 result.append("couldn't open ");
519 result.append(buffer);
520 result.append("\n");
521 }
522
Marco Nelissenf09611f2015-02-13 14:12:42 -0800523 gLooperRoster.dump(fd, args);
524
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800525 bool dumpMem = false;
Andy Hung53541292016-04-13 16:48:51 -0700526 bool unreachableMemory = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800527 for (size_t i = 0; i < args.size(); i++) {
528 if (args[i] == String16("-m")) {
529 dumpMem = true;
Andy Hung53541292016-04-13 16:48:51 -0700530 } else if (args[i] == String16("--unreachable")) {
531 unreachableMemory = true;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800532 }
533 }
534 if (dumpMem) {
Andy Hung07b745e2016-05-23 16:21:07 -0700535 result.append("\nDumping memory:\n");
536 std::string s = dumpMemoryAddresses(100 /* limit */);
537 result.append(s.c_str(), s.size());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800538 }
Andy Hung53541292016-04-13 16:48:51 -0700539 if (unreachableMemory) {
540 result.append("\nDumping unreachable memory:\n");
541 // TODO - should limit be an argument parameter?
542 std::string s = GetUnreachableMemoryString(true /* contents */, 10000 /* limit */);
543 result.append(s.c_str(), s.size());
544 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800545 }
546 write(fd, result.string(), result.size());
547 return NO_ERROR;
548}
549
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -0700550void MediaPlayerService::removeClient(const wp<Client>& client)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800551{
552 Mutex::Autolock lock(mLock);
553 mClients.remove(client);
554}
555
Robert Shihee0a0e32016-08-16 16:50:54 -0700556bool MediaPlayerService::hasClient(wp<Client> client)
557{
558 Mutex::Autolock lock(mLock);
559 return mClients.indexOf(client) != NAME_NOT_FOUND;
560}
561
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700562MediaPlayerService::Client::Client(
563 const sp<MediaPlayerService>& service, pid_t pid,
564 int32_t connId, const sp<IMediaPlayerClient>& client,
Glenn Kastend848eb42016-03-08 13:42:11 -0800565 audio_session_t audioSessionId, uid_t uid)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800566{
Steve Block3856b092011-10-20 11:56:00 +0100567 ALOGV("Client(%d) constructor", connId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800568 mPid = pid;
569 mConnId = connId;
570 mService = service;
571 mClient = client;
572 mLoop = false;
573 mStatus = NO_INIT;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700574 mAudioSessionId = audioSessionId;
Andy Hung1afd0982016-11-08 16:13:44 -0800575 mUid = uid;
John Grossmanc795b642012-02-22 15:38:35 -0800576 mRetransmitEndpointValid = false;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700577 mAudioAttributes = NULL;
Pawin Vongmasa082e4f72017-12-17 02:31:18 -0800578 mListener = new Listener(this);
Eric Laurenta514bdb2010-06-21 09:27:30 -0700579
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800580#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000581 ALOGD("create Antagonizer");
Pawin Vongmasa082e4f72017-12-17 02:31:18 -0800582 mAntagonizer = new Antagonizer(mListener);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800583#endif
584}
585
586MediaPlayerService::Client::~Client()
587{
Steve Block3856b092011-10-20 11:56:00 +0100588 ALOGV("Client(%d) destructor pid = %d", mConnId, mPid);
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700589 mAudioOutput.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800590 wp<Client> client(this);
591 disconnect();
592 mService->removeClient(client);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700593 if (mAudioAttributes != NULL) {
594 free(mAudioAttributes);
595 }
jiabin156c6872017-10-06 09:47:15 -0700596 mAudioDeviceUpdatedListener.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800597}
598
599void MediaPlayerService::Client::disconnect()
600{
Steve Block3856b092011-10-20 11:56:00 +0100601 ALOGV("disconnect(%d) from pid %d", mConnId, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800602 // grab local reference and clear main reference to prevent future
603 // access to object
604 sp<MediaPlayerBase> p;
605 {
606 Mutex::Autolock l(mLock);
607 p = mPlayer;
beanzdcfefde2012-11-05 09:51:43 +0800608 mClient.clear();
Wei Jia502c2f42017-07-13 17:47:56 -0700609 mPlayer.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800610 }
Andreas Huber20111aa2009-07-14 16:56:47 -0700611
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800612 // clear the notification to prevent callbacks to dead client
613 // and reset the player. We assume the player will serialize
614 // access to itself if necessary.
615 if (p != 0) {
Pawin Vongmasa082e4f72017-12-17 02:31:18 -0800616 p->setNotifyCallback(0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800617#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000618 ALOGD("kill Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800619 mAntagonizer->kill();
620#endif
621 p->reset();
622 }
623
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700624 {
625 Mutex::Autolock l(mLock);
626 disconnectNativeWindow_l();
627 }
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700628
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800629 IPCThreadState::self()->flushCommands();
630}
631
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800632sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
633{
634 // determine if we have the right player type
Wei Jia502c2f42017-07-13 17:47:56 -0700635 sp<MediaPlayerBase> p = getPlayer();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800636 if ((p != NULL) && (p->playerType() != playerType)) {
Steve Block3856b092011-10-20 11:56:00 +0100637 ALOGV("delete player");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800638 p.clear();
639 }
640 if (p == NULL) {
Pawin Vongmasa082e4f72017-12-17 02:31:18 -0800641 p = MediaPlayerFactory::createPlayer(playerType, mListener, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800642 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700643
Jason Simmonsdb29e522011-08-12 13:46:55 -0700644 if (p != NULL) {
Andy Hung1afd0982016-11-08 16:13:44 -0800645 p->setUID(mUid);
Jason Simmonsdb29e522011-08-12 13:46:55 -0700646 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700647
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800648 return p;
649}
650
jiabin156c6872017-10-06 09:47:15 -0700651void MediaPlayerService::Client::AudioDeviceUpdatedNotifier::onAudioDeviceUpdate(
652 audio_io_handle_t audioIo,
653 audio_port_handle_t deviceId) {
654 sp<MediaPlayerBase> listener = mListener.promote();
655 if (listener != NULL) {
656 listener->sendEvent(MEDIA_AUDIO_ROUTING_CHANGED, audioIo, deviceId);
657 } else {
658 ALOGW("listener for process %d death is gone", MEDIA_AUDIO_ROUTING_CHANGED);
659 }
660}
661
John Grossmanc795b642012-02-22 15:38:35 -0800662sp<MediaPlayerBase> MediaPlayerService::Client::setDataSource_pre(
663 player_type playerType)
664{
665 ALOGV("player type = %d", playerType);
666
667 // create the right type of player
668 sp<MediaPlayerBase> p = createPlayer(playerType);
669 if (p == NULL) {
670 return p;
671 }
672
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700673 std::vector<DeathNotifier> deathNotifiers;
674
675 // Listen to death of media.extractor service
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700676 sp<IServiceManager> sm = defaultServiceManager();
677 sp<IBinder> binder = sm->getService(String16("media.extractor"));
Marco Nelissen1b5a7ee2016-09-30 13:54:30 -0700678 if (binder == NULL) {
679 ALOGE("extractor service not available");
680 return NULL;
681 }
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700682 deathNotifiers.emplace_back(
683 binder, [l = wp<MediaPlayerBase>(p)]() {
684 sp<MediaPlayerBase> listener = l.promote();
685 if (listener) {
686 ALOGI("media.extractor died. Sending death notification.");
687 listener->sendEvent(MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED,
688 MEDIAEXTRACTOR_PROCESS_DEATH);
689 } else {
690 ALOGW("media.extractor died without a death handler.");
691 }
692 });
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700693
Marco Nelissena0c98412019-03-29 12:10:19 -0700694 {
695 using ::android::hidl::base::V1_0::IBase;
696
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700697 // Listen to death of OMX service
Marco Nelissena0c98412019-03-29 12:10:19 -0700698 {
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700699 sp<IBase> base = ::android::hardware::media::omx::V1_0::
700 IOmx::getService();
701 if (base == nullptr) {
Marco Nelissena0c98412019-03-29 12:10:19 -0700702 ALOGD("OMX service is not available");
703 } else {
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700704 deathNotifiers.emplace_back(
705 base, [l = wp<MediaPlayerBase>(p)]() {
706 sp<MediaPlayerBase> listener = l.promote();
707 if (listener) {
708 ALOGI("OMX service died. "
709 "Sending death notification.");
710 listener->sendEvent(
711 MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED,
712 MEDIACODEC_PROCESS_DEATH);
713 } else {
714 ALOGW("OMX service died without a death handler.");
715 }
716 });
Marco Nelissena0c98412019-03-29 12:10:19 -0700717 }
718 }
719
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700720 // Listen to death of Codec2 services
Marco Nelissena0c98412019-03-29 12:10:19 -0700721 {
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700722 for (std::shared_ptr<Codec2Client> const& client :
723 Codec2Client::CreateFromAllServices()) {
724 sp<IBase> base = client->getBase();
725 deathNotifiers.emplace_back(
726 base, [l = wp<MediaPlayerBase>(p),
727 name = std::string(client->getServiceName())]() {
728 sp<MediaPlayerBase> listener = l.promote();
729 if (listener) {
730 ALOGI("Codec2 service \"%s\" died. "
731 "Sending death notification.",
732 name.c_str());
733 listener->sendEvent(
734 MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED,
735 MEDIACODEC_PROCESS_DEATH);
736 } else {
737 ALOGW("Codec2 service \"%s\" died "
738 "without a death handler.",
739 name.c_str());
740 }
741 });
Marco Nelissene4da6c62019-04-01 15:01:41 -0700742 }
Marco Nelissena0c98412019-03-29 12:10:19 -0700743 }
Marco Nelissen1b5a7ee2016-09-30 13:54:30 -0700744 }
Marco Nelissen6dc3a3e2016-04-29 15:42:06 -0700745
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700746 Mutex::Autolock lock(mLock);
747
Pawin Vongmasa270dd6a2019-04-06 04:41:15 -0700748 mDeathNotifiers.clear();
749 mDeathNotifiers.swap(deathNotifiers);
jiabin156c6872017-10-06 09:47:15 -0700750 mAudioDeviceUpdatedListener = new AudioDeviceUpdatedNotifier(p);
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700751
John Grossmanc795b642012-02-22 15:38:35 -0800752 if (!p->hardwareOutput()) {
Marco Nelissend457c972014-02-11 08:47:07 -0800753 mAudioOutput = new AudioOutput(mAudioSessionId, IPCThreadState::self()->getCallingUid(),
jiabin156c6872017-10-06 09:47:15 -0700754 mPid, mAudioAttributes, mAudioDeviceUpdatedListener);
John Grossmanc795b642012-02-22 15:38:35 -0800755 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
756 }
757
758 return p;
759}
760
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700761status_t MediaPlayerService::Client::setDataSource_post(
John Grossmanc795b642012-02-22 15:38:35 -0800762 const sp<MediaPlayerBase>& p,
763 status_t status)
764{
765 ALOGV(" setDataSource");
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700766 if (status != OK) {
767 ALOGE(" error: %d", status);
768 return status;
John Grossmanc795b642012-02-22 15:38:35 -0800769 }
770
771 // Set the re-transmission endpoint if one was chosen.
772 if (mRetransmitEndpointValid) {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700773 status = p->setRetransmitEndpoint(&mRetransmitEndpoint);
774 if (status != NO_ERROR) {
775 ALOGE("setRetransmitEndpoint error: %d", status);
John Grossmanc795b642012-02-22 15:38:35 -0800776 }
777 }
778
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700779 if (status == OK) {
780 Mutex::Autolock lock(mLock);
John Grossmanc795b642012-02-22 15:38:35 -0800781 mPlayer = p;
782 }
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700783 return status;
John Grossmanc795b642012-02-22 15:38:35 -0800784}
785
Andreas Huber2db84552010-01-28 11:19:57 -0800786status_t MediaPlayerService::Client::setDataSource(
Andreas Huber1b86fe02014-01-29 11:13:26 -0800787 const sp<IMediaHTTPService> &httpService,
788 const char *url,
789 const KeyedVector<String8, String8> *headers)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800790{
Steve Block3856b092011-10-20 11:56:00 +0100791 ALOGV("setDataSource(%s)", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800792 if (url == NULL)
793 return UNKNOWN_ERROR;
794
Dave Burked681bbb2011-08-30 14:39:17 +0100795 if ((strncmp(url, "http://", 7) == 0) ||
796 (strncmp(url, "https://", 8) == 0) ||
797 (strncmp(url, "rtsp://", 7) == 0)) {
798 if (!checkPermission("android.permission.INTERNET")) {
799 return PERMISSION_DENIED;
800 }
801 }
802
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800803 if (strncmp(url, "content://", 10) == 0) {
804 // get a filedescriptor for the content Uri and
805 // pass it to the setDataSource(fd) method
806
807 String16 url16(url);
808 int fd = android::openContentProviderFile(url16);
809 if (fd < 0)
810 {
Steve Block29357bc2012-01-06 19:20:56 +0000811 ALOGE("Couldn't open fd for %s", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800812 return UNKNOWN_ERROR;
813 }
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700814 status_t status = setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800815 close(fd);
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700816 return mStatus = status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800817 } else {
John Grossman44a7e422012-06-21 17:29:24 -0700818 player_type playerType = MediaPlayerFactory::getPlayerType(this, url);
John Grossmanc795b642012-02-22 15:38:35 -0800819 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
820 if (p == NULL) {
821 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800822 }
823
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700824 return mStatus =
825 setDataSource_post(
826 p, p->setDataSource(httpService, url, headers));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800827 }
828}
829
830status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
831{
Marco Nelissen83b0fd92015-09-16 13:48:07 -0700832 ALOGV("setDataSource fd=%d (%s), offset=%lld, length=%lld",
833 fd, nameForFd(fd).c_str(), (long long) offset, (long long) length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800834 struct stat sb;
835 int ret = fstat(fd, &sb);
836 if (ret != 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000837 ALOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800838 return UNKNOWN_ERROR;
839 }
840
Andy Hung833b4752016-04-04 17:15:48 -0700841 ALOGV("st_dev = %llu", static_cast<unsigned long long>(sb.st_dev));
Steve Block3856b092011-10-20 11:56:00 +0100842 ALOGV("st_mode = %u", sb.st_mode);
Mark Salyzyn77342f72014-06-18 16:31:32 -0700843 ALOGV("st_uid = %lu", static_cast<unsigned long>(sb.st_uid));
844 ALOGV("st_gid = %lu", static_cast<unsigned long>(sb.st_gid));
Andy Hung833b4752016-04-04 17:15:48 -0700845 ALOGV("st_size = %llu", static_cast<unsigned long long>(sb.st_size));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800846
847 if (offset >= sb.st_size) {
Steve Block29357bc2012-01-06 19:20:56 +0000848 ALOGE("offset error");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800849 return UNKNOWN_ERROR;
850 }
851 if (offset + length > sb.st_size) {
852 length = sb.st_size - offset;
Andy Hung833b4752016-04-04 17:15:48 -0700853 ALOGV("calculated length = %lld", (long long)length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800854 }
855
John Grossman44a7e422012-06-21 17:29:24 -0700856 player_type playerType = MediaPlayerFactory::getPlayerType(this,
857 fd,
858 offset,
859 length);
John Grossmanc795b642012-02-22 15:38:35 -0800860 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
861 if (p == NULL) {
862 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800863 }
864
865 // now set data source
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700866 return mStatus = setDataSource_post(p, p->setDataSource(fd, offset, length));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800867}
868
Andreas Hubere2b10282010-11-23 11:41:34 -0800869status_t MediaPlayerService::Client::setDataSource(
870 const sp<IStreamSource> &source) {
871 // create the right type of player
John Grossman44a7e422012-06-21 17:29:24 -0700872 player_type playerType = MediaPlayerFactory::getPlayerType(this, source);
John Grossmanc795b642012-02-22 15:38:35 -0800873 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
Andreas Hubere2b10282010-11-23 11:41:34 -0800874 if (p == NULL) {
875 return NO_INIT;
876 }
877
Andreas Hubere2b10282010-11-23 11:41:34 -0800878 // now set data source
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700879 return mStatus = setDataSource_post(p, p->setDataSource(source));
Andreas Hubere2b10282010-11-23 11:41:34 -0800880}
881
Chris Watkins99f31602015-03-20 13:06:33 -0700882status_t MediaPlayerService::Client::setDataSource(
883 const sp<IDataSource> &source) {
Dongwon Kangd91dc5a2017-10-10 00:07:09 -0700884 sp<DataSource> dataSource = CreateDataSourceFromIDataSource(source);
Chris Watkins99f31602015-03-20 13:06:33 -0700885 player_type playerType = MediaPlayerFactory::getPlayerType(this, dataSource);
886 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
887 if (p == NULL) {
888 return NO_INIT;
889 }
890 // now set data source
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700891 return mStatus = setDataSource_post(p, p->setDataSource(dataSource));
Chris Watkins99f31602015-03-20 13:06:33 -0700892}
893
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700894void MediaPlayerService::Client::disconnectNativeWindow_l() {
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700895 if (mConnectedWindow != NULL) {
Chong Zhang181fd9b2017-02-16 15:53:03 -0800896 status_t err = nativeWindowDisconnect(
897 mConnectedWindow.get(), "disconnectNativeWindow");
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700898
899 if (err != OK) {
Chong Zhang181fd9b2017-02-16 15:53:03 -0800900 ALOGW("nativeWindowDisconnect returned an error: %s (%d)",
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700901 strerror(-err), err);
902 }
903 }
904 mConnectedWindow.clear();
905}
906
Glenn Kasten11731182011-02-08 17:26:17 -0800907status_t MediaPlayerService::Client::setVideoSurfaceTexture(
Andy McFadden484566c2012-12-18 09:46:54 -0800908 const sp<IGraphicBufferProducer>& bufferProducer)
Glenn Kasten11731182011-02-08 17:26:17 -0800909{
Andy McFadden484566c2012-12-18 09:46:54 -0800910 ALOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, bufferProducer.get());
Glenn Kasten11731182011-02-08 17:26:17 -0800911 sp<MediaPlayerBase> p = getPlayer();
912 if (p == 0) return UNKNOWN_ERROR;
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700913
Marco Nelissenf8880202014-11-14 07:58:25 -0800914 sp<IBinder> binder(IInterface::asBinder(bufferProducer));
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700915 if (mConnectedWindowBinder == binder) {
916 return OK;
917 }
918
919 sp<ANativeWindow> anw;
Andy McFadden484566c2012-12-18 09:46:54 -0800920 if (bufferProducer != NULL) {
Marco Nelissenee08f7e2013-09-16 13:30:01 -0700921 anw = new Surface(bufferProducer, true /* controlledByApp */);
Chong Zhang181fd9b2017-02-16 15:53:03 -0800922 status_t err = nativeWindowConnect(anw.get(), "setVideoSurfaceTexture");
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700923
924 if (err != OK) {
Steve Block29357bc2012-01-06 19:20:56 +0000925 ALOGE("setVideoSurfaceTexture failed: %d", err);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700926 // Note that we must do the reset before disconnecting from the ANW.
927 // Otherwise queue/dequeue calls could be made on the disconnected
928 // ANW, which may result in errors.
929 reset();
930
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700931 Mutex::Autolock lock(mLock);
932 disconnectNativeWindow_l();
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700933
934 return err;
935 }
936 }
937
Andy McFadden484566c2012-12-18 09:46:54 -0800938 // Note that we must set the player's new GraphicBufferProducer before
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700939 // disconnecting the old one. Otherwise queue/dequeue calls could be made
940 // on the disconnected ANW, which may result in errors.
Andy McFadden484566c2012-12-18 09:46:54 -0800941 status_t err = p->setVideoSurfaceTexture(bufferProducer);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700942
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700943 mLock.lock();
944 disconnectNativeWindow_l();
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700945
946 if (err == OK) {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700947 mConnectedWindow = anw;
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700948 mConnectedWindowBinder = binder;
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700949 mLock.unlock();
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700950 } else {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -0700951 mLock.unlock();
952 status_t err = nativeWindowDisconnect(
953 anw.get(), "disconnectNativeWindow");
954
955 if (err != OK) {
956 ALOGW("nativeWindowDisconnect returned an error: %s (%d)",
957 strerror(-err), err);
958 }
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700959 }
960
961 return err;
Glenn Kasten11731182011-02-08 17:26:17 -0800962}
963
Nicolas Catania1d187f12009-05-12 23:25:55 -0700964status_t MediaPlayerService::Client::invoke(const Parcel& request,
965 Parcel *reply)
966{
967 sp<MediaPlayerBase> p = getPlayer();
968 if (p == NULL) return UNKNOWN_ERROR;
969 return p->invoke(request, reply);
970}
971
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700972// This call doesn't need to access the native player.
973status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
974{
975 status_t status;
nikoa64c8c72009-07-20 15:07:26 -0700976 media::Metadata::Filter allow, drop;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700977
Nicolas Catania48290382009-07-10 13:53:06 -0700978 if (unmarshallFilter(filter, &allow, &status) &&
979 unmarshallFilter(filter, &drop, &status)) {
980 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700981
982 mMetadataAllow = allow;
983 mMetadataDrop = drop;
984 }
985 return status;
986}
987
Nicolas Catania48290382009-07-10 13:53:06 -0700988status_t MediaPlayerService::Client::getMetadata(
Mark Salyzyn77342f72014-06-18 16:31:32 -0700989 bool update_only, bool /*apply_filter*/, Parcel *reply)
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700990{
nikoa64c8c72009-07-20 15:07:26 -0700991 sp<MediaPlayerBase> player = getPlayer();
992 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania48290382009-07-10 13:53:06 -0700993
nikod608a812009-07-16 16:39:53 -0700994 status_t status;
995 // Placeholder for the return code, updated by the caller.
996 reply->writeInt32(-1);
997
nikoa64c8c72009-07-20 15:07:26 -0700998 media::Metadata::Filter ids;
Nicolas Catania48290382009-07-10 13:53:06 -0700999
1000 // We don't block notifications while we fetch the data. We clear
1001 // mMetadataUpdated first so we don't lose notifications happening
1002 // during the rest of this call.
1003 {
1004 Mutex::Autolock lock(mLock);
1005 if (update_only) {
nikod608a812009-07-16 16:39:53 -07001006 ids = mMetadataUpdated;
Nicolas Catania48290382009-07-10 13:53:06 -07001007 }
1008 mMetadataUpdated.clear();
1009 }
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001010
nikoa64c8c72009-07-20 15:07:26 -07001011 media::Metadata metadata(reply);
Nicolas Catania48290382009-07-10 13:53:06 -07001012
nikoa64c8c72009-07-20 15:07:26 -07001013 metadata.appendHeader();
1014 status = player->getMetadata(ids, reply);
nikod608a812009-07-16 16:39:53 -07001015
1016 if (status != OK) {
nikoa64c8c72009-07-20 15:07:26 -07001017 metadata.resetParcel();
Steve Block29357bc2012-01-06 19:20:56 +00001018 ALOGE("getMetadata failed %d", status);
nikod608a812009-07-16 16:39:53 -07001019 return status;
1020 }
1021
1022 // FIXME: Implement filtering on the result. Not critical since
1023 // filtering takes place on the update notifications already. This
1024 // would be when all the metadata are fetch and a filter is set.
1025
nikod608a812009-07-16 16:39:53 -07001026 // Everything is fine, update the metadata length.
nikoa64c8c72009-07-20 15:07:26 -07001027 metadata.updateLength();
nikod608a812009-07-16 16:39:53 -07001028 return OK;
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -07001029}
1030
Wei Jiad399e7e2016-10-26 15:49:11 -07001031status_t MediaPlayerService::Client::setBufferingSettings(
1032 const BufferingSettings& buffering)
1033{
Wei Jiadc6f3402017-01-09 15:04:18 -08001034 ALOGV("[%d] setBufferingSettings{%s}",
1035 mConnId, buffering.toString().string());
Wei Jiad399e7e2016-10-26 15:49:11 -07001036 sp<MediaPlayerBase> p = getPlayer();
1037 if (p == 0) return UNKNOWN_ERROR;
1038 return p->setBufferingSettings(buffering);
1039}
1040
Wei Jia9bb38032017-03-23 18:00:38 -07001041status_t MediaPlayerService::Client::getBufferingSettings(
Wei Jiad399e7e2016-10-26 15:49:11 -07001042 BufferingSettings* buffering /* nonnull */)
1043{
1044 sp<MediaPlayerBase> p = getPlayer();
1045 // TODO: create mPlayer on demand.
1046 if (p == 0) return UNKNOWN_ERROR;
Wei Jia9bb38032017-03-23 18:00:38 -07001047 status_t ret = p->getBufferingSettings(buffering);
Wei Jiad399e7e2016-10-26 15:49:11 -07001048 if (ret == NO_ERROR) {
Wei Jia9bb38032017-03-23 18:00:38 -07001049 ALOGV("[%d] getBufferingSettings{%s}",
Wei Jiadc6f3402017-01-09 15:04:18 -08001050 mConnId, buffering->toString().string());
Wei Jiad399e7e2016-10-26 15:49:11 -07001051 } else {
Wei Jia9bb38032017-03-23 18:00:38 -07001052 ALOGE("[%d] getBufferingSettings returned %d", mConnId, ret);
Wei Jiad399e7e2016-10-26 15:49:11 -07001053 }
1054 return ret;
1055}
1056
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001057status_t MediaPlayerService::Client::prepareAsync()
1058{
Steve Block3856b092011-10-20 11:56:00 +01001059 ALOGV("[%d] prepareAsync", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001060 sp<MediaPlayerBase> p = getPlayer();
1061 if (p == 0) return UNKNOWN_ERROR;
1062 status_t ret = p->prepareAsync();
1063#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +00001064 ALOGD("start Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001065 if (ret == NO_ERROR) mAntagonizer->start();
1066#endif
1067 return ret;
1068}
1069
1070status_t MediaPlayerService::Client::start()
1071{
Steve Block3856b092011-10-20 11:56:00 +01001072 ALOGV("[%d] start", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001073 sp<MediaPlayerBase> p = getPlayer();
1074 if (p == 0) return UNKNOWN_ERROR;
1075 p->setLooping(mLoop);
1076 return p->start();
1077}
1078
1079status_t MediaPlayerService::Client::stop()
1080{
Steve Block3856b092011-10-20 11:56:00 +01001081 ALOGV("[%d] stop", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001082 sp<MediaPlayerBase> p = getPlayer();
1083 if (p == 0) return UNKNOWN_ERROR;
1084 return p->stop();
1085}
1086
1087status_t MediaPlayerService::Client::pause()
1088{
Steve Block3856b092011-10-20 11:56:00 +01001089 ALOGV("[%d] pause", 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->pause();
1093}
1094
1095status_t MediaPlayerService::Client::isPlaying(bool* state)
1096{
1097 *state = false;
1098 sp<MediaPlayerBase> p = getPlayer();
1099 if (p == 0) return UNKNOWN_ERROR;
1100 *state = p->isPlaying();
Steve Block3856b092011-10-20 11:56:00 +01001101 ALOGV("[%d] isPlaying: %d", mConnId, *state);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001102 return NO_ERROR;
1103}
1104
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001105status_t MediaPlayerService::Client::setPlaybackSettings(const AudioPlaybackRate& rate)
Wei Jia98160162015-02-04 17:01:11 -08001106{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001107 ALOGV("[%d] setPlaybackSettings(%f, %f, %d, %d)",
1108 mConnId, rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Wei Jia98160162015-02-04 17:01:11 -08001109 sp<MediaPlayerBase> p = getPlayer();
1110 if (p == 0) return UNKNOWN_ERROR;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001111 return p->setPlaybackSettings(rate);
1112}
1113
1114status_t MediaPlayerService::Client::getPlaybackSettings(AudioPlaybackRate* rate /* nonnull */)
1115{
1116 sp<MediaPlayerBase> p = getPlayer();
1117 if (p == 0) return UNKNOWN_ERROR;
1118 status_t ret = p->getPlaybackSettings(rate);
1119 if (ret == NO_ERROR) {
1120 ALOGV("[%d] getPlaybackSettings(%f, %f, %d, %d)",
1121 mConnId, rate->mSpeed, rate->mPitch, rate->mFallbackMode, rate->mStretchMode);
1122 } else {
1123 ALOGV("[%d] getPlaybackSettings returned %d", mConnId, ret);
1124 }
1125 return ret;
1126}
1127
1128status_t MediaPlayerService::Client::setSyncSettings(
1129 const AVSyncSettings& sync, float videoFpsHint)
1130{
1131 ALOGV("[%d] setSyncSettings(%u, %u, %f, %f)",
1132 mConnId, sync.mSource, sync.mAudioAdjustMode, sync.mTolerance, videoFpsHint);
1133 sp<MediaPlayerBase> p = getPlayer();
1134 if (p == 0) return UNKNOWN_ERROR;
1135 return p->setSyncSettings(sync, videoFpsHint);
1136}
1137
1138status_t MediaPlayerService::Client::getSyncSettings(
1139 AVSyncSettings* sync /* nonnull */, float* videoFps /* nonnull */)
1140{
1141 sp<MediaPlayerBase> p = getPlayer();
1142 if (p == 0) return UNKNOWN_ERROR;
1143 status_t ret = p->getSyncSettings(sync, videoFps);
1144 if (ret == NO_ERROR) {
1145 ALOGV("[%d] getSyncSettings(%u, %u, %f, %f)",
1146 mConnId, sync->mSource, sync->mAudioAdjustMode, sync->mTolerance, *videoFps);
1147 } else {
1148 ALOGV("[%d] getSyncSettings returned %d", mConnId, ret);
1149 }
1150 return ret;
Wei Jia98160162015-02-04 17:01:11 -08001151}
1152
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001153status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
1154{
Steve Block3856b092011-10-20 11:56:00 +01001155 ALOGV("getCurrentPosition");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001156 sp<MediaPlayerBase> p = getPlayer();
1157 if (p == 0) return UNKNOWN_ERROR;
1158 status_t ret = p->getCurrentPosition(msec);
1159 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001160 ALOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001161 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001162 ALOGE("getCurrentPosition returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001163 }
1164 return ret;
1165}
1166
1167status_t MediaPlayerService::Client::getDuration(int *msec)
1168{
Steve Block3856b092011-10-20 11:56:00 +01001169 ALOGV("getDuration");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001170 sp<MediaPlayerBase> p = getPlayer();
1171 if (p == 0) return UNKNOWN_ERROR;
1172 status_t ret = p->getDuration(msec);
1173 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001174 ALOGV("[%d] getDuration = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001175 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001176 ALOGE("getDuration returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001177 }
1178 return ret;
1179}
1180
Marco Nelissen6b74d672012-02-28 16:07:44 -08001181status_t MediaPlayerService::Client::setNextPlayer(const sp<IMediaPlayer>& player) {
1182 ALOGV("setNextPlayer");
1183 Mutex::Autolock l(mLock);
1184 sp<Client> c = static_cast<Client*>(player.get());
Wei Jia28284122016-08-30 13:49:06 -07001185 if (c != NULL && !mService->hasClient(c)) {
Robert Shihee0a0e32016-08-16 16:50:54 -07001186 return BAD_VALUE;
1187 }
1188
Marco Nelissen6b74d672012-02-28 16:07:44 -08001189 mNextClient = c;
John Grossman5f7e55e2012-08-24 14:47:25 -07001190
1191 if (c != NULL) {
1192 if (mAudioOutput != NULL) {
1193 mAudioOutput->setNextOutput(c->mAudioOutput);
1194 } else if ((mPlayer != NULL) && !mPlayer->hardwareOutput()) {
1195 ALOGE("no current audio output");
1196 }
1197
1198 if ((mPlayer != NULL) && (mNextClient->getPlayer() != NULL)) {
1199 mPlayer->setNextPlayer(mNextClient->getPlayer());
1200 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001201 }
John Grossman5f7e55e2012-08-24 14:47:25 -07001202
Marco Nelissen6b74d672012-02-28 16:07:44 -08001203 return OK;
1204}
1205
Andy Hung9fc8b5c2017-01-24 13:36:48 -08001206VolumeShaper::Status MediaPlayerService::Client::applyVolumeShaper(
1207 const sp<VolumeShaper::Configuration>& configuration,
1208 const sp<VolumeShaper::Operation>& operation) {
1209 // for hardware output, call player instead
1210 ALOGV("Client::applyVolumeShaper(%p)", this);
1211 sp<MediaPlayerBase> p = getPlayer();
1212 {
1213 Mutex::Autolock l(mLock);
1214 if (p != 0 && p->hardwareOutput()) {
1215 // TODO: investigate internal implementation
1216 return VolumeShaper::Status(INVALID_OPERATION);
1217 }
1218 if (mAudioOutput.get() != nullptr) {
1219 return mAudioOutput->applyVolumeShaper(configuration, operation);
1220 }
1221 }
1222 return VolumeShaper::Status(INVALID_OPERATION);
1223}
1224
1225sp<VolumeShaper::State> MediaPlayerService::Client::getVolumeShaperState(int id) {
1226 // for hardware output, call player instead
1227 ALOGV("Client::getVolumeShaperState(%p)", this);
1228 sp<MediaPlayerBase> p = getPlayer();
1229 {
1230 Mutex::Autolock l(mLock);
1231 if (p != 0 && p->hardwareOutput()) {
1232 // TODO: investigate internal implementation.
1233 return nullptr;
1234 }
1235 if (mAudioOutput.get() != nullptr) {
1236 return mAudioOutput->getVolumeShaperState(id);
1237 }
1238 }
1239 return nullptr;
1240}
1241
Wei Jiac5de0912016-11-18 10:22:14 -08001242status_t MediaPlayerService::Client::seekTo(int msec, MediaPlayerSeekMode mode)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001243{
Wei Jiac5de0912016-11-18 10:22:14 -08001244 ALOGV("[%d] seekTo(%d, %d)", mConnId, msec, mode);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001245 sp<MediaPlayerBase> p = getPlayer();
1246 if (p == 0) return UNKNOWN_ERROR;
Wei Jiac5de0912016-11-18 10:22:14 -08001247 return p->seekTo(msec, mode);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001248}
1249
1250status_t MediaPlayerService::Client::reset()
1251{
Steve Block3856b092011-10-20 11:56:00 +01001252 ALOGV("[%d] reset", mConnId);
John Grossmanc795b642012-02-22 15:38:35 -08001253 mRetransmitEndpointValid = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001254 sp<MediaPlayerBase> p = getPlayer();
1255 if (p == 0) return UNKNOWN_ERROR;
1256 return p->reset();
1257}
1258
Wei Jia52c28512017-09-13 18:17:51 -07001259status_t MediaPlayerService::Client::notifyAt(int64_t mediaTimeUs)
1260{
1261 ALOGV("[%d] notifyAt(%lld)", mConnId, (long long)mediaTimeUs);
1262 sp<MediaPlayerBase> p = getPlayer();
1263 if (p == 0) return UNKNOWN_ERROR;
1264 return p->notifyAt(mediaTimeUs);
1265}
1266
Glenn Kastenfff6d712012-01-12 16:38:12 -08001267status_t MediaPlayerService::Client::setAudioStreamType(audio_stream_type_t type)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001268{
Steve Block3856b092011-10-20 11:56:00 +01001269 ALOGV("[%d] setAudioStreamType(%d)", mConnId, type);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001270 // TODO: for hardware output, call player instead
1271 Mutex::Autolock l(mLock);
1272 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1273 return NO_ERROR;
1274}
1275
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001276status_t MediaPlayerService::Client::setAudioAttributes_l(const Parcel &parcel)
1277{
1278 if (mAudioAttributes != NULL) { free(mAudioAttributes); }
1279 mAudioAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001280 if (mAudioAttributes == NULL) {
1281 return NO_MEMORY;
1282 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001283 unmarshallAudioAttributes(parcel, mAudioAttributes);
1284
1285 ALOGV("setAudioAttributes_l() usage=%d content=%d flags=0x%x tags=%s",
1286 mAudioAttributes->usage, mAudioAttributes->content_type, mAudioAttributes->flags,
1287 mAudioAttributes->tags);
1288
1289 if (mAudioOutput != 0) {
1290 mAudioOutput->setAudioAttributes(mAudioAttributes);
1291 }
1292 return NO_ERROR;
1293}
1294
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001295status_t MediaPlayerService::Client::setLooping(int loop)
1296{
Steve Block3856b092011-10-20 11:56:00 +01001297 ALOGV("[%d] setLooping(%d)", mConnId, loop);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001298 mLoop = loop;
1299 sp<MediaPlayerBase> p = getPlayer();
1300 if (p != 0) return p->setLooping(loop);
1301 return NO_ERROR;
1302}
1303
1304status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1305{
Steve Block3856b092011-10-20 11:56:00 +01001306 ALOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
John Grossman761defc2012-02-09 15:09:05 -08001307
1308 // for hardware output, call player instead
1309 sp<MediaPlayerBase> p = getPlayer();
1310 {
1311 Mutex::Autolock l(mLock);
1312 if (p != 0 && p->hardwareOutput()) {
1313 MediaPlayerHWInterface* hwp =
1314 reinterpret_cast<MediaPlayerHWInterface*>(p.get());
1315 return hwp->setVolume(leftVolume, rightVolume);
1316 } else {
1317 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1318 return NO_ERROR;
1319 }
1320 }
1321
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001322 return NO_ERROR;
1323}
1324
Eric Laurent2beeb502010-07-16 07:43:46 -07001325status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1326{
Steve Block3856b092011-10-20 11:56:00 +01001327 ALOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
Eric Laurent2beeb502010-07-16 07:43:46 -07001328 Mutex::Autolock l(mLock);
1329 if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1330 return NO_ERROR;
1331}
1332
1333status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1334{
Steve Block3856b092011-10-20 11:56:00 +01001335 ALOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
Eric Laurent2beeb502010-07-16 07:43:46 -07001336 Mutex::Autolock l(mLock);
1337 if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1338 return NO_ERROR;
1339}
Nicolas Catania48290382009-07-10 13:53:06 -07001340
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001341status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
Steve Block3856b092011-10-20 11:56:00 +01001342 ALOGV("[%d] setParameter(%d)", mConnId, key);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001343 switch (key) {
1344 case KEY_PARAMETER_AUDIO_ATTRIBUTES:
1345 {
1346 Mutex::Autolock l(mLock);
1347 return setAudioAttributes_l(request);
1348 }
1349 default:
1350 sp<MediaPlayerBase> p = getPlayer();
1351 if (p == 0) { return UNKNOWN_ERROR; }
1352 return p->setParameter(key, request);
1353 }
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001354}
1355
1356status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
Steve Block3856b092011-10-20 11:56:00 +01001357 ALOGV("[%d] getParameter(%d)", mConnId, key);
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001358 sp<MediaPlayerBase> p = getPlayer();
1359 if (p == 0) return UNKNOWN_ERROR;
1360 return p->getParameter(key, reply);
1361}
1362
John Grossmanc795b642012-02-22 15:38:35 -08001363status_t MediaPlayerService::Client::setRetransmitEndpoint(
1364 const struct sockaddr_in* endpoint) {
1365
1366 if (NULL != endpoint) {
1367 uint32_t a = ntohl(endpoint->sin_addr.s_addr);
1368 uint16_t p = ntohs(endpoint->sin_port);
1369 ALOGV("[%d] setRetransmitEndpoint(%u.%u.%u.%u:%hu)", mConnId,
1370 (a >> 24), (a >> 16) & 0xFF, (a >> 8) & 0xFF, (a & 0xFF), p);
1371 } else {
1372 ALOGV("[%d] setRetransmitEndpoint = <none>", mConnId);
1373 }
1374
1375 sp<MediaPlayerBase> p = getPlayer();
1376
1377 // Right now, the only valid time to set a retransmit endpoint is before
1378 // player selection has been made (since the presence or absence of a
1379 // retransmit endpoint is going to determine which player is selected during
1380 // setDataSource).
1381 if (p != 0) return INVALID_OPERATION;
1382
1383 if (NULL != endpoint) {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001384 Mutex::Autolock lock(mLock);
John Grossmanc795b642012-02-22 15:38:35 -08001385 mRetransmitEndpoint = *endpoint;
1386 mRetransmitEndpointValid = true;
1387 } else {
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001388 Mutex::Autolock lock(mLock);
John Grossmanc795b642012-02-22 15:38:35 -08001389 mRetransmitEndpointValid = false;
1390 }
1391
1392 return NO_ERROR;
1393}
1394
John Grossman44a7e422012-06-21 17:29:24 -07001395status_t MediaPlayerService::Client::getRetransmitEndpoint(
1396 struct sockaddr_in* endpoint)
1397{
1398 if (NULL == endpoint)
1399 return BAD_VALUE;
1400
1401 sp<MediaPlayerBase> p = getPlayer();
1402
1403 if (p != NULL)
1404 return p->getRetransmitEndpoint(endpoint);
1405
Pawin Vongmasaf9c81462017-09-28 05:31:11 -07001406 Mutex::Autolock lock(mLock);
John Grossman44a7e422012-06-21 17:29:24 -07001407 if (!mRetransmitEndpointValid)
1408 return NO_INIT;
1409
1410 *endpoint = mRetransmitEndpoint;
1411
1412 return NO_ERROR;
1413}
1414
Gloria Wangb483c472011-04-11 17:23:27 -07001415void MediaPlayerService::Client::notify(
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001416 int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001417{
James Dongb8a98252012-08-26 16:13:03 -07001418 sp<IMediaPlayerClient> c;
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001419 sp<Client> nextClient;
1420 status_t errStartNext = NO_ERROR;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001421 {
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001422 Mutex::Autolock l(mLock);
1423 c = mClient;
1424 if (msg == MEDIA_PLAYBACK_COMPLETE && mNextClient != NULL) {
1425 nextClient = mNextClient;
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001426
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001427 if (mAudioOutput != NULL)
1428 mAudioOutput->switchToNextOutput();
Haynes Mathew George6cb33752015-06-22 14:16:42 -07001429
1430 errStartNext = nextClient->start();
1431 }
1432 }
1433
1434 if (nextClient != NULL) {
1435 sp<IMediaPlayerClient> nc;
1436 {
1437 Mutex::Autolock l(nextClient->mLock);
1438 nc = nextClient->mClient;
1439 }
1440 if (nc != NULL) {
1441 if (errStartNext == NO_ERROR) {
1442 nc->notify(MEDIA_INFO, MEDIA_INFO_STARTED_AS_NEXT, 0, obj);
1443 } else {
1444 nc->notify(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN , 0, obj);
1445 ALOGE("gapless:start playback for next track failed, err(%d)", errStartNext);
Wei Jia2afac0c2016-01-07 12:13:07 -08001446 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001447 }
1448 }
1449
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001450 if (MEDIA_INFO == msg &&
Nicolas Catania48290382009-07-10 13:53:06 -07001451 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikoa64c8c72009-07-20 15:07:26 -07001452 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania48290382009-07-10 13:53:06 -07001453
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001454 if(shouldDropMetadata(metadata_type)) {
Nicolas Catania48290382009-07-10 13:53:06 -07001455 return;
1456 }
1457
1458 // Update the list of metadata that have changed. getMetadata
1459 // also access mMetadataUpdated and clears it.
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001460 addNewMetadataUpdate(metadata_type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001461 }
James Dongb8a98252012-08-26 16:13:03 -07001462
1463 if (c != NULL) {
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001464 ALOGV("[%d] notify (%d, %d, %d)", mConnId, msg, ext1, ext2);
James Dongb8a98252012-08-26 16:13:03 -07001465 c->notify(msg, ext1, ext2, obj);
1466 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001467}
1468
Nicolas Catania48290382009-07-10 13:53:06 -07001469
nikoa64c8c72009-07-20 15:07:26 -07001470bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001471{
Nicolas Catania48290382009-07-10 13:53:06 -07001472 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001473
Nicolas Catania48290382009-07-10 13:53:06 -07001474 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001475 return true;
1476 }
1477
Nicolas Catania48290382009-07-10 13:53:06 -07001478 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001479 return false;
Nicolas Catania48290382009-07-10 13:53:06 -07001480 } else {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001481 return true;
1482 }
1483}
1484
Nicolas Catania48290382009-07-10 13:53:06 -07001485
nikoa64c8c72009-07-20 15:07:26 -07001486void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania48290382009-07-10 13:53:06 -07001487 Mutex::Autolock lock(mLock);
1488 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1489 mMetadataUpdated.add(metadata_type);
1490 }
1491}
1492
Hassan Shojaniacefac142017-02-06 21:02:02 -08001493// Modular DRM
1494status_t MediaPlayerService::Client::prepareDrm(const uint8_t uuid[16],
1495 const Vector<uint8_t>& drmSessionId)
1496{
1497 ALOGV("[%d] prepareDrm", mConnId);
1498 sp<MediaPlayerBase> p = getPlayer();
1499 if (p == 0) return UNKNOWN_ERROR;
1500
1501 status_t ret = p->prepareDrm(uuid, drmSessionId);
1502 ALOGV("prepareDrm ret: %d", ret);
1503
1504 return ret;
1505}
1506
1507status_t MediaPlayerService::Client::releaseDrm()
1508{
1509 ALOGV("[%d] releaseDrm", mConnId);
1510 sp<MediaPlayerBase> p = getPlayer();
1511 if (p == 0) return UNKNOWN_ERROR;
1512
1513 status_t ret = p->releaseDrm();
1514 ALOGV("releaseDrm ret: %d", ret);
1515
1516 return ret;
1517}
1518
jiabin156c6872017-10-06 09:47:15 -07001519status_t MediaPlayerService::Client::setOutputDevice(audio_port_handle_t deviceId)
1520{
1521 ALOGV("[%d] setOutputDevice", mConnId);
1522 {
1523 Mutex::Autolock l(mLock);
1524 if (mAudioOutput.get() != nullptr) {
1525 return mAudioOutput->setOutputDevice(deviceId);
1526 }
1527 }
1528 return NO_INIT;
1529}
1530
1531status_t MediaPlayerService::Client::getRoutedDeviceId(audio_port_handle_t* deviceId)
1532{
1533 ALOGV("[%d] getRoutedDeviceId", mConnId);
1534 {
1535 Mutex::Autolock l(mLock);
1536 if (mAudioOutput.get() != nullptr) {
1537 return mAudioOutput->getRoutedDeviceId(deviceId);
1538 }
1539 }
1540 return NO_INIT;
1541}
1542
1543status_t MediaPlayerService::Client::enableAudioDeviceCallback(bool enabled)
1544{
1545 ALOGV("[%d] enableAudioDeviceCallback, %d", mConnId, enabled);
1546 {
1547 Mutex::Autolock l(mLock);
1548 if (mAudioOutput.get() != nullptr) {
1549 return mAudioOutput->enableAudioDeviceCallback(enabled);
1550 }
1551 }
1552 return NO_INIT;
1553}
1554
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001555#if CALLBACK_ANTAGONIZER
1556const int Antagonizer::interval = 10000; // 10 msecs
1557
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001558Antagonizer::Antagonizer(const sp<MediaPlayerBase::Listener> &listener) :
1559 mExit(false), mActive(false), mListener(listener)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001560{
1561 createThread(callbackThread, this);
1562}
1563
1564void Antagonizer::kill()
1565{
1566 Mutex::Autolock _l(mLock);
1567 mActive = false;
1568 mExit = true;
1569 mCondition.wait(mLock);
1570}
1571
1572int Antagonizer::callbackThread(void* user)
1573{
Steve Blockb8a80522011-12-20 16:23:08 +00001574 ALOGD("Antagonizer started");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001575 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1576 while (!p->mExit) {
1577 if (p->mActive) {
Steve Block3856b092011-10-20 11:56:00 +01001578 ALOGV("send event");
Pawin Vongmasa082e4f72017-12-17 02:31:18 -08001579 p->mListener->notify(0, 0, 0, 0);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001580 }
1581 usleep(interval);
1582 }
1583 Mutex::Autolock _l(p->mLock);
1584 p->mCondition.signal();
Steve Blockb8a80522011-12-20 16:23:08 +00001585 ALOGD("Antagonizer stopped");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001586 return 0;
1587}
1588#endif
1589
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001590#undef LOG_TAG
1591#define LOG_TAG "AudioSink"
Andy Hung1afd0982016-11-08 16:13:44 -08001592MediaPlayerService::AudioOutput::AudioOutput(audio_session_t sessionId, uid_t uid, int pid,
jiabin156c6872017-10-06 09:47:15 -07001593 const audio_attributes_t* attr, const sp<AudioSystem::AudioDeviceCallback>& deviceCallback)
Andreas Huber20111aa2009-07-14 16:56:47 -07001594 : mCallback(NULL),
Eric Laurenta514bdb2010-06-21 09:27:30 -07001595 mCallbackCookie(NULL),
Marco Nelissen6b74d672012-02-28 16:07:44 -08001596 mCallbackData(NULL),
Andy Hungd1c74342015-07-07 16:54:23 -07001597 mStreamType(AUDIO_STREAM_MUSIC),
Andy Hungd1c74342015-07-07 16:54:23 -07001598 mLeftVolume(1.0),
1599 mRightVolume(1.0),
1600 mPlaybackRate(AUDIO_PLAYBACK_RATE_DEFAULT),
1601 mSampleRateHz(0),
1602 mMsecsPerFrame(0),
1603 mFrameSize(0),
Eric Laurent1948eb32012-04-13 16:50:19 -07001604 mSessionId(sessionId),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001605 mUid(uid),
Marco Nelissend457c972014-02-11 08:47:07 -08001606 mPid(pid),
Andy Hungd1c74342015-07-07 16:54:23 -07001607 mSendLevel(0.0),
1608 mAuxEffectId(0),
Andy Hung4ef88d72017-02-21 19:47:53 -08001609 mFlags(AUDIO_OUTPUT_FLAG_NONE),
jiabin156c6872017-10-06 09:47:15 -07001610 mVolumeHandler(new media::VolumeHandler()),
1611 mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE),
jiabin161b64fc2017-11-17 09:31:48 -08001612 mRoutedDeviceId(AUDIO_PORT_HANDLE_NONE),
jiabin156c6872017-10-06 09:47:15 -07001613 mDeviceCallbackEnabled(false),
1614 mDeviceCallback(deviceCallback)
Andy Hungd1c74342015-07-07 16:54:23 -07001615{
Steve Block3856b092011-10-20 11:56:00 +01001616 ALOGV("AudioOutput(%d)", sessionId);
Eric Laurent43562692015-07-15 16:49:07 -07001617 if (attr != NULL) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001618 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1619 if (mAttributes != NULL) {
1620 memcpy(mAttributes, attr, sizeof(audio_attributes_t));
François Gaffie58d4be52018-11-06 15:30:12 +01001621 mStreamType = AudioSystem::attributesToStreamType(*attr);
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001622 }
1623 } else {
1624 mAttributes = NULL;
Eric Laurent43562692015-07-15 16:49:07 -07001625 }
1626
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001627 setMinBufferCount();
1628}
1629
1630MediaPlayerService::AudioOutput::~AudioOutput()
1631{
1632 close();
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001633 free(mAttributes);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001634 delete mCallbackData;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001635}
1636
Andy Hungd1c74342015-07-07 16:54:23 -07001637//static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001638void MediaPlayerService::AudioOutput::setMinBufferCount()
1639{
1640 char value[PROPERTY_VALUE_MAX];
1641 if (property_get("ro.kernel.qemu", value, 0)) {
1642 mIsOnEmulator = true;
1643 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1644 }
1645}
1646
Andy Hungd1c74342015-07-07 16:54:23 -07001647// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001648bool MediaPlayerService::AudioOutput::isOnEmulator()
1649{
Andy Hungd1c74342015-07-07 16:54:23 -07001650 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001651 return mIsOnEmulator;
1652}
1653
Andy Hungd1c74342015-07-07 16:54:23 -07001654// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001655int MediaPlayerService::AudioOutput::getMinBufferCount()
1656{
Andy Hungd1c74342015-07-07 16:54:23 -07001657 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001658 return mMinBufferCount;
1659}
1660
1661ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1662{
Andy Hungd1c74342015-07-07 16:54:23 -07001663 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001664 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001665 return mTrack->frameCount() * mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001666}
1667
1668ssize_t MediaPlayerService::AudioOutput::frameCount() const
1669{
Andy Hungd1c74342015-07-07 16:54:23 -07001670 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001671 if (mTrack == 0) return NO_INIT;
1672 return mTrack->frameCount();
1673}
1674
1675ssize_t MediaPlayerService::AudioOutput::channelCount() const
1676{
Andy Hungd1c74342015-07-07 16:54:23 -07001677 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001678 if (mTrack == 0) return NO_INIT;
1679 return mTrack->channelCount();
1680}
1681
1682ssize_t MediaPlayerService::AudioOutput::frameSize() const
1683{
Andy Hungd1c74342015-07-07 16:54:23 -07001684 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001685 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001686 return mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001687}
1688
1689uint32_t MediaPlayerService::AudioOutput::latency () const
1690{
Andy Hungd1c74342015-07-07 16:54:23 -07001691 Mutex::Autolock lock(mLock);
Eric Laurentdb354e52012-03-05 17:27:11 -08001692 if (mTrack == 0) return 0;
1693 return mTrack->latency();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001694}
1695
1696float MediaPlayerService::AudioOutput::msecsPerFrame() const
1697{
Andy Hungd1c74342015-07-07 16:54:23 -07001698 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001699 return mMsecsPerFrame;
1700}
1701
Marco Nelissen4110c102012-03-29 09:31:28 -07001702status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position) const
Eric Laurent342e9cf2010-01-19 17:37:09 -08001703{
Andy Hungd1c74342015-07-07 16:54:23 -07001704 Mutex::Autolock lock(mLock);
Eric Laurent342e9cf2010-01-19 17:37:09 -08001705 if (mTrack == 0) return NO_INIT;
1706 return mTrack->getPosition(position);
1707}
1708
Lajos Molnar06ad1522014-08-28 07:27:44 -07001709status_t MediaPlayerService::AudioOutput::getTimestamp(AudioTimestamp &ts) const
1710{
Andy Hungd1c74342015-07-07 16:54:23 -07001711 Mutex::Autolock lock(mLock);
Lajos Molnar06ad1522014-08-28 07:27:44 -07001712 if (mTrack == 0) return NO_INIT;
1713 return mTrack->getTimestamp(ts);
1714}
1715
Wei Jiac4ac8172015-10-21 10:35:48 -07001716// TODO: Remove unnecessary calls to getPlayedOutDurationUs()
1717// as it acquires locks and may query the audio driver.
1718//
1719// Some calls could conceivably retrieve extrapolated data instead of
1720// accessing getTimestamp() or getPosition() every time a data buffer with
1721// a media time is received.
1722//
1723// Calculate duration of played samples if played at normal rate (i.e., 1.0).
1724int64_t MediaPlayerService::AudioOutput::getPlayedOutDurationUs(int64_t nowUs) const
1725{
1726 Mutex::Autolock lock(mLock);
1727 if (mTrack == 0 || mSampleRateHz == 0) {
Wei Jia213f4902015-10-22 08:55:25 -07001728 return 0;
Wei Jiac4ac8172015-10-21 10:35:48 -07001729 }
1730
1731 uint32_t numFramesPlayed;
Andy Hung5d313802016-10-10 15:09:39 -07001732 int64_t numFramesPlayedAtUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001733 AudioTimestamp ts;
Wei Jiac4ac8172015-10-21 10:35:48 -07001734
1735 status_t res = mTrack->getTimestamp(ts);
1736 if (res == OK) { // case 1: mixing audio tracks and offloaded tracks.
1737 numFramesPlayed = ts.mPosition;
Andy Hung5d313802016-10-10 15:09:39 -07001738 numFramesPlayedAtUs = ts.mTime.tv_sec * 1000000LL + ts.mTime.tv_nsec / 1000;
1739 //ALOGD("getTimestamp: OK %d %lld", numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001740 } else if (res == WOULD_BLOCK) { // case 2: transitory state on start of a new track
1741 numFramesPlayed = 0;
Andy Hung5d313802016-10-10 15:09:39 -07001742 numFramesPlayedAtUs = nowUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001743 //ALOGD("getTimestamp: WOULD_BLOCK %d %lld",
Andy Hung5d313802016-10-10 15:09:39 -07001744 // numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001745 } else { // case 3: transitory at new track or audio fast tracks.
1746 res = mTrack->getPosition(&numFramesPlayed);
1747 CHECK_EQ(res, (status_t)OK);
Andy Hung5d313802016-10-10 15:09:39 -07001748 numFramesPlayedAtUs = nowUs;
1749 numFramesPlayedAtUs += 1000LL * mTrack->latency() / 2; /* XXX */
1750 //ALOGD("getPosition: %u %lld", numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001751 }
1752
1753 // CHECK_EQ(numFramesPlayed & (1 << 31), 0); // can't be negative until 12.4 hrs, test
1754 // TODO: remove the (int32_t) casting below as it may overflow at 12.4 hours.
1755 int64_t durationUs = (int64_t)((int32_t)numFramesPlayed * 1000000LL / mSampleRateHz)
Andy Hung5d313802016-10-10 15:09:39 -07001756 + nowUs - numFramesPlayedAtUs;
Wei Jiac4ac8172015-10-21 10:35:48 -07001757 if (durationUs < 0) {
1758 // Occurs when numFramesPlayed position is very small and the following:
1759 // (1) In case 1, the time nowUs is computed before getTimestamp() is called and
Andy Hung5d313802016-10-10 15:09:39 -07001760 // numFramesPlayedAtUs is greater than nowUs by time more than numFramesPlayed.
Wei Jiac4ac8172015-10-21 10:35:48 -07001761 // (2) In case 3, using getPosition and adding mAudioSink->latency() to
Andy Hung5d313802016-10-10 15:09:39 -07001762 // numFramesPlayedAtUs, by a time amount greater than numFramesPlayed.
Wei Jiac4ac8172015-10-21 10:35:48 -07001763 //
1764 // Both of these are transitory conditions.
1765 ALOGV("getPlayedOutDurationUs: negative duration %lld set to zero", (long long)durationUs);
1766 durationUs = 0;
1767 }
1768 ALOGV("getPlayedOutDurationUs(%lld) nowUs(%lld) frames(%u) framesAt(%lld)",
Andy Hung5d313802016-10-10 15:09:39 -07001769 (long long)durationUs, (long long)nowUs,
1770 numFramesPlayed, (long long)numFramesPlayedAtUs);
Wei Jiac4ac8172015-10-21 10:35:48 -07001771 return durationUs;
1772}
1773
Marco Nelissen4110c102012-03-29 09:31:28 -07001774status_t MediaPlayerService::AudioOutput::getFramesWritten(uint32_t *frameswritten) const
1775{
Andy Hungd1c74342015-07-07 16:54:23 -07001776 Mutex::Autolock lock(mLock);
Marco Nelissen4110c102012-03-29 09:31:28 -07001777 if (mTrack == 0) return NO_INIT;
Andy Hung2f6e73d2016-04-08 12:12:58 -07001778 ExtendedTimestamp ets;
1779 status_t status = mTrack->getTimestamp(&ets);
1780 if (status == OK || status == WOULD_BLOCK) {
1781 *frameswritten = (uint32_t)ets.mPosition[ExtendedTimestamp::LOCATION_CLIENT];
1782 }
1783 return status;
Marco Nelissen4110c102012-03-29 09:31:28 -07001784}
1785
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001786status_t MediaPlayerService::AudioOutput::setParameters(const String8& keyValuePairs)
1787{
Andy Hungd1c74342015-07-07 16:54:23 -07001788 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001789 if (mTrack == 0) return NO_INIT;
1790 return mTrack->setParameters(keyValuePairs);
1791}
1792
1793String8 MediaPlayerService::AudioOutput::getParameters(const String8& keys)
1794{
Andy Hungd1c74342015-07-07 16:54:23 -07001795 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001796 if (mTrack == 0) return String8::empty();
1797 return mTrack->getParameters(keys);
1798}
1799
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001800void MediaPlayerService::AudioOutput::setAudioAttributes(const audio_attributes_t * attributes) {
Andy Hungd1c74342015-07-07 16:54:23 -07001801 Mutex::Autolock lock(mLock);
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001802 if (attributes == NULL) {
1803 free(mAttributes);
1804 mAttributes = NULL;
1805 } else {
1806 if (mAttributes == NULL) {
1807 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1808 }
1809 memcpy(mAttributes, attributes, sizeof(audio_attributes_t));
François Gaffie58d4be52018-11-06 15:30:12 +01001810 mStreamType = AudioSystem::attributesToStreamType(*attributes);
Eric Laurent43562692015-07-15 16:49:07 -07001811 }
1812}
1813
1814void MediaPlayerService::AudioOutput::setAudioStreamType(audio_stream_type_t streamType)
1815{
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001816 Mutex::Autolock lock(mLock);
Eric Laurent43562692015-07-15 16:49:07 -07001817 // do not allow direct stream type modification if attributes have been set
1818 if (mAttributes == NULL) {
1819 mStreamType = streamType;
1820 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001821}
1822
Andy Hungd1c74342015-07-07 16:54:23 -07001823void MediaPlayerService::AudioOutput::deleteRecycledTrack_l()
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001824{
Andy Hungd1c74342015-07-07 16:54:23 -07001825 ALOGV("deleteRecycledTrack_l");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001826 if (mRecycledTrack != 0) {
1827
1828 if (mCallbackData != NULL) {
1829 mCallbackData->setOutput(NULL);
1830 mCallbackData->endTrackSwitch();
1831 }
1832
1833 if ((mRecycledTrack->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) {
Andy Hunge13f8a62016-03-30 14:20:42 -07001834 int32_t msec = 0;
1835 if (!mRecycledTrack->stopped()) { // check if active
1836 (void)mRecycledTrack->pendingDuration(&msec);
1837 }
1838 mRecycledTrack->stop(); // ensure full data drain
1839 ALOGD("deleting recycled track, waiting for data drain (%d msec)", msec);
1840 if (msec > 0) {
1841 static const int32_t WAIT_LIMIT_MS = 3000;
1842 if (msec > WAIT_LIMIT_MS) {
1843 msec = WAIT_LIMIT_MS;
1844 }
1845 usleep(msec * 1000LL);
1846 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001847 }
1848 // An offloaded track isn't flushed because the STREAM_END is reported
1849 // slightly prematurely to allow time for the gapless track switch
1850 // but this means that if we decide not to recycle the track there
1851 // could be a small amount of residual data still playing. We leave
1852 // AudioFlinger to drain the track.
1853
1854 mRecycledTrack.clear();
Andy Hungd1c74342015-07-07 16:54:23 -07001855 close_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001856 delete mCallbackData;
1857 mCallbackData = NULL;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001858 }
1859}
1860
Andy Hungd1c74342015-07-07 16:54:23 -07001861void MediaPlayerService::AudioOutput::close_l()
1862{
1863 mTrack.clear();
1864}
1865
Andreas Huber20111aa2009-07-14 16:56:47 -07001866status_t MediaPlayerService::AudioOutput::open(
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001867 uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
1868 audio_format_t format, int bufferCount,
Eric Laurent1948eb32012-04-13 16:50:19 -07001869 AudioCallback cb, void *cookie,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001870 audio_output_flags_t flags,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001871 const audio_offload_info_t *offloadInfo,
Andy Hung179652e2015-05-31 22:49:46 -07001872 bool doNotReconnect,
1873 uint32_t suggestedFrameCount)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001874{
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001875 ALOGV("open(%u, %d, 0x%x, 0x%x, %d, %d 0x%x)", sampleRate, channelCount, channelMask,
1876 format, bufferCount, mSessionId, flags);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001877
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001878 // offloading is only supported in callback mode for now.
1879 // offloadInfo must be present if offload flag is set
1880 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) &&
1881 ((cb == NULL) || (offloadInfo == NULL))) {
1882 return BAD_VALUE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001883 }
1884
Andy Hung179652e2015-05-31 22:49:46 -07001885 // compute frame count for the AudioTrack internal buffer
1886 size_t frameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001887 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1888 frameCount = 0; // AudioTrack will get frame count from AudioFlinger
1889 } else {
Andy Hung179652e2015-05-31 22:49:46 -07001890 // try to estimate the buffer processing fetch size from AudioFlinger.
1891 // framesPerBuffer is approximate and generally correct, except when it's not :-).
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001892 uint32_t afSampleRate;
1893 size_t afFrameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001894 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1895 return NO_INIT;
1896 }
1897 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1898 return NO_INIT;
1899 }
Ben Romberger259fb462018-08-07 17:58:53 -07001900 if (afSampleRate == 0) {
1901 return NO_INIT;
1902 }
Andy Hung179652e2015-05-31 22:49:46 -07001903 const size_t framesPerBuffer =
1904 (unsigned long long)sampleRate * afFrameCount / afSampleRate;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001905
Andy Hung179652e2015-05-31 22:49:46 -07001906 if (bufferCount == 0) {
Ben Romberger259fb462018-08-07 17:58:53 -07001907 if (framesPerBuffer == 0) {
1908 return NO_INIT;
1909 }
Andy Hung179652e2015-05-31 22:49:46 -07001910 // use suggestedFrameCount
1911 bufferCount = (suggestedFrameCount + framesPerBuffer - 1) / framesPerBuffer;
1912 }
1913 // Check argument bufferCount against the mininum buffer count
1914 if (bufferCount != 0 && bufferCount < mMinBufferCount) {
1915 ALOGV("bufferCount (%d) increased to %d", bufferCount, mMinBufferCount);
1916 bufferCount = mMinBufferCount;
1917 }
1918 // if frameCount is 0, then AudioTrack will get frame count from AudioFlinger
1919 // which will be the minimum size permitted.
1920 frameCount = bufferCount * framesPerBuffer;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001921 }
Andreas Huber20111aa2009-07-14 16:56:47 -07001922
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001923 if (channelMask == CHANNEL_MASK_USE_CHANNEL_ORDER) {
Glenn Kastenab334fd2012-03-14 12:56:06 -07001924 channelMask = audio_channel_out_mask_from_count(channelCount);
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001925 if (0 == channelMask) {
1926 ALOGE("open() error, can\'t derive mask for %d audio channels", channelCount);
1927 return NO_INIT;
1928 }
1929 }
Eric Laurent1948eb32012-04-13 16:50:19 -07001930
Andy Hungd1c74342015-07-07 16:54:23 -07001931 Mutex::Autolock lock(mLock);
Andy Hung179652e2015-05-31 22:49:46 -07001932 mCallback = cb;
1933 mCallbackCookie = cookie;
1934
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001935 // Check whether we can recycle the track
1936 bool reuse = false;
1937 bool bothOffloaded = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001938
Glenn Kasten2799d742013-05-30 14:33:29 -07001939 if (mRecycledTrack != 0) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001940 // check whether we are switching between two offloaded tracks
1941 bothOffloaded = (flags & mRecycledTrack->getFlags()
1942 & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0;
Marco Nelissen67295b52012-06-11 14:52:53 -07001943
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001944 // check if the existing track can be reused as-is, or if a new track needs to be created.
1945 reuse = true;
1946
Marco Nelissen67295b52012-06-11 14:52:53 -07001947 if ((mCallbackData == NULL && mCallback != NULL) ||
1948 (mCallbackData != NULL && mCallback == NULL)) {
1949 // recycled track uses callbacks but the caller wants to use writes, or vice versa
1950 ALOGV("can't chain callback and write");
1951 reuse = false;
1952 } else if ((mRecycledTrack->getSampleRate() != sampleRate) ||
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001953 (mRecycledTrack->channelCount() != (uint32_t)channelCount) ) {
1954 ALOGV("samplerate, channelcount differ: %u/%u Hz, %u/%d ch",
Marco Nelissen67295b52012-06-11 14:52:53 -07001955 mRecycledTrack->getSampleRate(), sampleRate,
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001956 mRecycledTrack->channelCount(), channelCount);
Marco Nelissen67295b52012-06-11 14:52:53 -07001957 reuse = false;
1958 } else if (flags != mFlags) {
1959 ALOGV("output flags differ %08x/%08x", flags, mFlags);
1960 reuse = false;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001961 } else if (mRecycledTrack->format() != format) {
1962 reuse = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001963 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001964 } else {
1965 ALOGV("no track available to recycle");
1966 }
1967
1968 ALOGV_IF(bothOffloaded, "both tracks offloaded");
1969
1970 // If we can't recycle and both tracks are offloaded
1971 // we must close the previous output before opening a new one
1972 if (bothOffloaded && !reuse) {
1973 ALOGV("both offloaded and not recycling");
Andy Hungd1c74342015-07-07 16:54:23 -07001974 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001975 }
1976
1977 sp<AudioTrack> t;
1978 CallbackData *newcbd = NULL;
1979
1980 // We don't attempt to create a new track if we are recycling an
1981 // offloaded track. But, if we are recycling a non-offloaded or we
1982 // are switching where one is offloaded and one isn't then we create
1983 // the new track in advance so that we can read additional stream info
1984
1985 if (!(reuse && bothOffloaded)) {
1986 ALOGV("creating new AudioTrack");
1987
1988 if (mCallback != NULL) {
1989 newcbd = new CallbackData(this);
1990 t = new AudioTrack(
1991 mStreamType,
1992 sampleRate,
1993 format,
1994 channelMask,
1995 frameCount,
1996 flags,
1997 CallbackWrapper,
1998 newcbd,
1999 0, // notification frames
2000 mSessionId,
2001 AudioTrack::TRANSFER_CALLBACK,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002002 offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -08002003 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07002004 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07002005 mAttributes,
jiabin156c6872017-10-06 09:47:15 -07002006 doNotReconnect,
2007 1.0f, // default value for maxRequiredSpeed
2008 mSelectedDeviceId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002009 } else {
Andy Hungff874dc2016-04-11 16:49:09 -07002010 // TODO: Due to buffer memory concerns, we use a max target playback speed
2011 // based on mPlaybackRate at the time of open (instead of kMaxRequiredSpeed),
2012 // also clamping the target speed to 1.0 <= targetSpeed <= kMaxRequiredSpeed.
2013 const float targetSpeed =
2014 std::min(std::max(mPlaybackRate.mSpeed, 1.0f), kMaxRequiredSpeed);
2015 ALOGW_IF(targetSpeed != mPlaybackRate.mSpeed,
2016 "track target speed:%f clamped from playback speed:%f",
2017 targetSpeed, mPlaybackRate.mSpeed);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002018 t = new AudioTrack(
2019 mStreamType,
2020 sampleRate,
2021 format,
2022 channelMask,
2023 frameCount,
2024 flags,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002025 NULL, // callback
2026 NULL, // user data
2027 0, // notification frames
2028 mSessionId,
2029 AudioTrack::TRANSFER_DEFAULT,
2030 NULL, // offload info
Marco Nelissend457c972014-02-11 08:47:07 -08002031 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07002032 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07002033 mAttributes,
Andy Hungff874dc2016-04-11 16:49:09 -07002034 doNotReconnect,
jiabin156c6872017-10-06 09:47:15 -07002035 targetSpeed,
2036 mSelectedDeviceId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002037 }
2038
2039 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
2040 ALOGE("Unable to create audio track");
2041 delete newcbd;
Glenn Kasten3e98ecd2015-05-18 13:13:24 -07002042 // t goes out of scope, so reference count drops to zero
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002043 return NO_INIT;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07002044 } else {
2045 // successful AudioTrack initialization implies a legacy stream type was generated
2046 // from the audio attributes
2047 mStreamType = t->streamType();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002048 }
2049 }
2050
2051 if (reuse) {
2052 CHECK(mRecycledTrack != NULL);
2053
2054 if (!bothOffloaded) {
2055 if (mRecycledTrack->frameCount() != t->frameCount()) {
Andy Hung833b4752016-04-04 17:15:48 -07002056 ALOGV("framecount differs: %zu/%zu frames",
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002057 mRecycledTrack->frameCount(), t->frameCount());
2058 reuse = false;
2059 }
2060 }
2061
Marco Nelissen67295b52012-06-11 14:52:53 -07002062 if (reuse) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002063 ALOGV("chaining to next output and recycling track");
Andy Hungd1c74342015-07-07 16:54:23 -07002064 close_l();
Marco Nelissen67295b52012-06-11 14:52:53 -07002065 mTrack = mRecycledTrack;
Glenn Kasten2799d742013-05-30 14:33:29 -07002066 mRecycledTrack.clear();
Marco Nelissen67295b52012-06-11 14:52:53 -07002067 if (mCallbackData != NULL) {
2068 mCallbackData->setOutput(this);
2069 }
Marco Nelissen67295b52012-06-11 14:52:53 -07002070 delete newcbd;
Wei Jiae0bbac92016-07-18 16:04:53 -07002071 return updateTrack();
Marco Nelissen67295b52012-06-11 14:52:53 -07002072 }
Marco Nelissen67295b52012-06-11 14:52:53 -07002073 }
2074
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002075 // we're not going to reuse the track, unblock and flush it
2076 // this was done earlier if both tracks are offloaded
2077 if (!bothOffloaded) {
Andy Hungd1c74342015-07-07 16:54:23 -07002078 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002079 }
2080
2081 CHECK((t != NULL) && ((mCallback == NULL) || (newcbd != NULL)));
2082
Marco Nelissen67295b52012-06-11 14:52:53 -07002083 mCallbackData = newcbd;
Steve Block3856b092011-10-20 11:56:00 +01002084 ALOGV("setVolume");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002085 t->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07002086
Andy Hung39399b62017-04-21 15:07:45 -07002087 // Restore VolumeShapers for the MediaPlayer in case the track was recreated
2088 // due to an output sink error (e.g. offload to non-offload switch).
2089 mVolumeHandler->forall([&t](const VolumeShaper &shaper) -> VolumeShaper::Status {
2090 sp<VolumeShaper::Operation> operationToEnd =
2091 new VolumeShaper::Operation(shaper.mOperation);
2092 // TODO: Ideally we would restore to the exact xOffset position
2093 // as returned by getVolumeShaperState(), but we don't have that
2094 // information when restoring at the client unless we periodically poll
2095 // the server or create shared memory state.
2096 //
2097 // For now, we simply advance to the end of the VolumeShaper effect
2098 // if it has been started.
2099 if (shaper.isStarted()) {
Andy Hungf3702642017-05-05 17:33:32 -07002100 operationToEnd->setNormalizedTime(1.f);
Andy Hung39399b62017-04-21 15:07:45 -07002101 }
2102 return t->applyVolumeShaper(shaper.mConfiguration, operationToEnd);
Andy Hung4ef88d72017-02-21 19:47:53 -08002103 });
Andy Hung4ef88d72017-02-21 19:47:53 -08002104
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002105 mSampleRateHz = sampleRate;
Preetam Singh Ranawat2e17eef2015-08-12 12:11:46 -07002106 mFlags = flags;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002107 mMsecsPerFrame = 1E3f / (mPlaybackRate.mSpeed * sampleRate);
Andy Hungd1c74342015-07-07 16:54:23 -07002108 mFrameSize = t->frameSize();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002109 mTrack = t;
Eric Laurent2beeb502010-07-16 07:43:46 -07002110
Wei Jiae0bbac92016-07-18 16:04:53 -07002111 return updateTrack();
2112}
2113
2114status_t MediaPlayerService::AudioOutput::updateTrack() {
2115 if (mTrack == NULL) {
2116 return NO_ERROR;
2117 }
2118
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002119 status_t res = NO_ERROR;
Wei Jia0162d002015-06-09 11:59:33 -07002120 // Note some output devices may give us a direct track even though we don't specify it.
2121 // Example: Line application b/17459982.
Wei Jiae0bbac92016-07-18 16:04:53 -07002122 if ((mTrack->getFlags()
2123 & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) {
2124 res = mTrack->setPlaybackRate(mPlaybackRate);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002125 if (res == NO_ERROR) {
Wei Jiae0bbac92016-07-18 16:04:53 -07002126 mTrack->setAuxEffectSendLevel(mSendLevel);
2127 res = mTrack->attachAuxEffect(mAuxEffectId);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002128 }
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002129 }
jiabin156c6872017-10-06 09:47:15 -07002130 mTrack->setOutputDevice(mSelectedDeviceId);
2131 if (mDeviceCallbackEnabled) {
2132 mTrack->addAudioDeviceCallback(mDeviceCallback.promote());
2133 }
Wei Jiae0bbac92016-07-18 16:04:53 -07002134 ALOGV("updateTrack() DONE status %d", res);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002135 return res;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002136}
2137
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002138status_t MediaPlayerService::AudioOutput::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002139{
Steve Block3856b092011-10-20 11:56:00 +01002140 ALOGV("start");
Andy Hungd1c74342015-07-07 16:54:23 -07002141 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08002142 if (mCallbackData != NULL) {
2143 mCallbackData->endTrackSwitch();
2144 }
Glenn Kasten2799d742013-05-30 14:33:29 -07002145 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002146 mTrack->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07002147 mTrack->setAuxEffectSendLevel(mSendLevel);
Andy Hung39399b62017-04-21 15:07:45 -07002148 status_t status = mTrack->start();
2149 if (status == NO_ERROR) {
2150 mVolumeHandler->setStarted();
2151 }
2152 return status;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002153 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002154 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002155}
2156
Marco Nelissen6b74d672012-02-28 16:07:44 -08002157void MediaPlayerService::AudioOutput::setNextOutput(const sp<AudioOutput>& nextOutput) {
Andy Hungd1c74342015-07-07 16:54:23 -07002158 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08002159 mNextOutput = nextOutput;
2160}
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08002161
Marco Nelissen6b74d672012-02-28 16:07:44 -08002162void MediaPlayerService::AudioOutput::switchToNextOutput() {
2163 ALOGV("switchToNextOutput");
Andy Hungd1c74342015-07-07 16:54:23 -07002164
2165 // Try to acquire the callback lock before moving track (without incurring deadlock).
2166 const unsigned kMaxSwitchTries = 100;
2167 Mutex::Autolock lock(mLock);
2168 for (unsigned tries = 0;;) {
2169 if (mTrack == 0) {
2170 return;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002171 }
Andy Hungd1c74342015-07-07 16:54:23 -07002172 if (mNextOutput != NULL && mNextOutput != this) {
2173 if (mCallbackData != NULL) {
2174 // two alternative approaches
2175#if 1
2176 CallbackData *callbackData = mCallbackData;
2177 mLock.unlock();
2178 // proper acquisition sequence
2179 callbackData->lock();
2180 mLock.lock();
2181 // Caution: it is unlikely that someone deleted our callback or changed our target
2182 if (callbackData != mCallbackData || mNextOutput == NULL || mNextOutput == this) {
2183 // fatal if we are starved out.
2184 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
2185 "switchToNextOutput() cannot obtain correct lock sequence");
2186 callbackData->unlock();
2187 continue;
2188 }
2189 callbackData->mSwitching = true; // begin track switch
Wei Jiaadee56a2016-08-05 15:40:34 -07002190 callbackData->setOutput(NULL);
Andy Hungd1c74342015-07-07 16:54:23 -07002191#else
2192 // tryBeginTrackSwitch() returns false if the callback has the lock.
2193 if (!mCallbackData->tryBeginTrackSwitch()) {
2194 // fatal if we are starved out.
2195 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
2196 "switchToNextOutput() cannot obtain callback lock");
2197 mLock.unlock();
2198 usleep(5 * 1000 /* usec */); // allow callback to use AudioOutput
2199 mLock.lock();
2200 continue;
2201 }
2202#endif
2203 }
2204
2205 Mutex::Autolock nextLock(mNextOutput->mLock);
2206
2207 // If the next output track is not NULL, then it has been
2208 // opened already for playback.
2209 // This is possible even without the next player being started,
2210 // for example, the next player could be prepared and seeked.
2211 //
2212 // Presuming it isn't advisable to force the track over.
2213 if (mNextOutput->mTrack == NULL) {
2214 ALOGD("Recycling track for gapless playback");
2215 delete mNextOutput->mCallbackData;
2216 mNextOutput->mCallbackData = mCallbackData;
2217 mNextOutput->mRecycledTrack = mTrack;
2218 mNextOutput->mSampleRateHz = mSampleRateHz;
2219 mNextOutput->mMsecsPerFrame = mMsecsPerFrame;
Andy Hungd1c74342015-07-07 16:54:23 -07002220 mNextOutput->mFlags = mFlags;
2221 mNextOutput->mFrameSize = mFrameSize;
2222 close_l();
2223 mCallbackData = NULL; // destruction handled by mNextOutput
2224 } else {
2225 ALOGW("Ignoring gapless playback because next player has already started");
2226 // remove track in case resource needed for future players.
2227 if (mCallbackData != NULL) {
2228 mCallbackData->endTrackSwitch(); // release lock for callbacks before close.
2229 }
2230 close_l();
2231 }
2232 }
2233 break;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002234 }
2235}
2236
Wei Jia7d3f4df2015-03-03 15:28:00 -08002237ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002238{
Andy Hungd1c74342015-07-07 16:54:23 -07002239 Mutex::Autolock lock(mLock);
Glenn Kastenadad3d72014-02-21 14:51:43 -08002240 LOG_ALWAYS_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
Andreas Huber20111aa2009-07-14 16:56:47 -07002241
Steve Block3856b092011-10-20 11:56:00 +01002242 //ALOGV("write(%p, %u)", buffer, size);
Glenn Kasten2799d742013-05-30 14:33:29 -07002243 if (mTrack != 0) {
Andy Hung2f6e73d2016-04-08 12:12:58 -07002244 return mTrack->write(buffer, size, blocking);
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07002245 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002246 return NO_INIT;
2247}
2248
2249void MediaPlayerService::AudioOutput::stop()
2250{
Steve Block3856b092011-10-20 11:56:00 +01002251 ALOGV("stop");
Andy Hungd1c74342015-07-07 16:54:23 -07002252 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002253 if (mTrack != 0) mTrack->stop();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002254}
2255
2256void MediaPlayerService::AudioOutput::flush()
2257{
Steve Block3856b092011-10-20 11:56:00 +01002258 ALOGV("flush");
Andy Hungd1c74342015-07-07 16:54:23 -07002259 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002260 if (mTrack != 0) mTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002261}
2262
2263void MediaPlayerService::AudioOutput::pause()
2264{
Steve Block3856b092011-10-20 11:56:00 +01002265 ALOGV("pause");
Andy Hungd1c74342015-07-07 16:54:23 -07002266 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07002267 if (mTrack != 0) mTrack->pause();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002268}
2269
2270void MediaPlayerService::AudioOutput::close()
2271{
Steve Block3856b092011-10-20 11:56:00 +01002272 ALOGV("close");
Erik Wolsheimer7845a1f2015-10-30 12:07:52 -07002273 sp<AudioTrack> track;
2274 {
2275 Mutex::Autolock lock(mLock);
2276 track = mTrack;
2277 close_l(); // clears mTrack
2278 }
2279 // destruction of the track occurs outside of mutex.
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002280}
2281
2282void MediaPlayerService::AudioOutput::setVolume(float left, float right)
2283{
Steve Block3856b092011-10-20 11:56:00 +01002284 ALOGV("setVolume(%f, %f)", left, right);
Andy Hungd1c74342015-07-07 16:54:23 -07002285 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002286 mLeftVolume = left;
2287 mRightVolume = right;
Glenn Kasten2799d742013-05-30 14:33:29 -07002288 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08002289 mTrack->setVolume(left, right);
2290 }
2291}
2292
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002293status_t MediaPlayerService::AudioOutput::setPlaybackRate(const AudioPlaybackRate &rate)
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002294{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002295 ALOGV("setPlaybackRate(%f %f %d %d)",
2296 rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Andy Hungd1c74342015-07-07 16:54:23 -07002297 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002298 if (mTrack == 0) {
2299 // remember rate so that we can set it when the track is opened
2300 mPlaybackRate = rate;
2301 return OK;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002302 }
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002303 status_t res = mTrack->setPlaybackRate(rate);
2304 if (res != NO_ERROR) {
2305 return res;
2306 }
2307 // rate.mSpeed is always greater than 0 if setPlaybackRate succeeded
2308 CHECK_GT(rate.mSpeed, 0.f);
2309 mPlaybackRate = rate;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002310 if (mSampleRateHz != 0) {
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002311 mMsecsPerFrame = 1E3f / (rate.mSpeed * mSampleRateHz);
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08002312 }
2313 return res;
2314}
2315
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002316status_t MediaPlayerService::AudioOutput::getPlaybackRate(AudioPlaybackRate *rate)
2317{
2318 ALOGV("setPlaybackRate");
Andy Hungd1c74342015-07-07 16:54:23 -07002319 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002320 if (mTrack == 0) {
2321 return NO_INIT;
2322 }
2323 *rate = mTrack->getPlaybackRate();
2324 return NO_ERROR;
2325}
2326
Eric Laurent2beeb502010-07-16 07:43:46 -07002327status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
2328{
Steve Block3856b092011-10-20 11:56:00 +01002329 ALOGV("setAuxEffectSendLevel(%f)", level);
Andy Hungd1c74342015-07-07 16:54:23 -07002330 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002331 mSendLevel = level;
Glenn Kasten2799d742013-05-30 14:33:29 -07002332 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002333 return mTrack->setAuxEffectSendLevel(level);
2334 }
2335 return NO_ERROR;
2336}
2337
2338status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
2339{
Steve Block3856b092011-10-20 11:56:00 +01002340 ALOGV("attachAuxEffect(%d)", effectId);
Andy Hungd1c74342015-07-07 16:54:23 -07002341 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002342 mAuxEffectId = effectId;
Glenn Kasten2799d742013-05-30 14:33:29 -07002343 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002344 return mTrack->attachAuxEffect(effectId);
2345 }
2346 return NO_ERROR;
2347}
2348
jiabin156c6872017-10-06 09:47:15 -07002349status_t MediaPlayerService::AudioOutput::setOutputDevice(audio_port_handle_t deviceId)
2350{
2351 ALOGV("setOutputDevice(%d)", deviceId);
2352 Mutex::Autolock lock(mLock);
2353 mSelectedDeviceId = deviceId;
2354 if (mTrack != 0) {
2355 return mTrack->setOutputDevice(deviceId);
2356 }
2357 return NO_ERROR;
2358}
2359
2360status_t MediaPlayerService::AudioOutput::getRoutedDeviceId(audio_port_handle_t* deviceId)
2361{
2362 ALOGV("getRoutedDeviceId");
2363 Mutex::Autolock lock(mLock);
2364 if (mTrack != 0) {
jiabin161b64fc2017-11-17 09:31:48 -08002365 mRoutedDeviceId = mTrack->getRoutedDeviceId();
jiabin156c6872017-10-06 09:47:15 -07002366 }
jiabin161b64fc2017-11-17 09:31:48 -08002367 *deviceId = mRoutedDeviceId;
2368 return NO_ERROR;
jiabin156c6872017-10-06 09:47:15 -07002369}
2370
2371status_t MediaPlayerService::AudioOutput::enableAudioDeviceCallback(bool enabled)
2372{
2373 ALOGV("enableAudioDeviceCallback, %d", enabled);
2374 Mutex::Autolock lock(mLock);
2375 mDeviceCallbackEnabled = enabled;
2376 if (mTrack != 0) {
2377 status_t status;
2378 if (enabled) {
2379 status = mTrack->addAudioDeviceCallback(mDeviceCallback.promote());
2380 } else {
2381 status = mTrack->removeAudioDeviceCallback(mDeviceCallback.promote());
2382 }
2383 return status;
2384 }
2385 return NO_ERROR;
2386}
2387
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002388VolumeShaper::Status MediaPlayerService::AudioOutput::applyVolumeShaper(
2389 const sp<VolumeShaper::Configuration>& configuration,
2390 const sp<VolumeShaper::Operation>& operation)
2391{
2392 Mutex::Autolock lock(mLock);
2393 ALOGV("AudioOutput::applyVolumeShaper");
Andy Hung4ef88d72017-02-21 19:47:53 -08002394
Andy Hung4ef88d72017-02-21 19:47:53 -08002395 mVolumeHandler->setIdIfNecessary(configuration);
Andy Hung39399b62017-04-21 15:07:45 -07002396
2397 VolumeShaper::Status status;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002398 if (mTrack != 0) {
Andy Hung39399b62017-04-21 15:07:45 -07002399 status = mTrack->applyVolumeShaper(configuration, operation);
2400 if (status >= 0) {
2401 (void)mVolumeHandler->applyVolumeShaper(configuration, operation);
Andy Hungf3702642017-05-05 17:33:32 -07002402 if (mTrack->isPlaying()) { // match local AudioTrack to properly restore.
2403 mVolumeHandler->setStarted();
2404 }
Andy Hung39399b62017-04-21 15:07:45 -07002405 }
Andy Hung4ef88d72017-02-21 19:47:53 -08002406 } else {
Andy Hungc01eddb2017-07-21 16:42:41 -07002407 // VolumeShapers are not affected when a track moves between players for
2408 // gapless playback (setNextMediaPlayer).
2409 // We forward VolumeShaper operations that do not change configuration
2410 // to the new player so that unducking may occur as expected.
2411 // Unducking is an idempotent operation, same if applied back-to-back.
2412 if (configuration->getType() == VolumeShaper::Configuration::TYPE_ID
2413 && mNextOutput != nullptr) {
2414 ALOGV("applyVolumeShaper: Attempting to forward missed operation: %s %s",
2415 configuration->toString().c_str(), operation->toString().c_str());
2416 Mutex::Autolock nextLock(mNextOutput->mLock);
2417
2418 // recycled track should be forwarded from this AudioSink by switchToNextOutput
2419 sp<AudioTrack> track = mNextOutput->mRecycledTrack;
2420 if (track != nullptr) {
2421 ALOGD("Forward VolumeShaper operation to recycled track %p", track.get());
2422 (void)track->applyVolumeShaper(configuration, operation);
2423 } else {
2424 // There is a small chance that the unduck occurs after the next
2425 // player has already started, but before it is registered to receive
2426 // the unduck command.
2427 track = mNextOutput->mTrack;
2428 if (track != nullptr) {
2429 ALOGD("Forward VolumeShaper operation to track %p", track.get());
2430 (void)track->applyVolumeShaper(configuration, operation);
2431 }
2432 }
2433 }
Andy Hung39399b62017-04-21 15:07:45 -07002434 status = mVolumeHandler->applyVolumeShaper(configuration, operation);
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002435 }
Andy Hung39399b62017-04-21 15:07:45 -07002436 return status;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002437}
2438
2439sp<VolumeShaper::State> MediaPlayerService::AudioOutput::getVolumeShaperState(int id)
2440{
2441 Mutex::Autolock lock(mLock);
2442 if (mTrack != 0) {
2443 return mTrack->getVolumeShaperState(id);
Andy Hung4ef88d72017-02-21 19:47:53 -08002444 } else {
2445 return mVolumeHandler->getVolumeShaperState(id);
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002446 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08002447}
2448
Andreas Huber20111aa2009-07-14 16:56:47 -07002449// static
2450void MediaPlayerService::AudioOutput::CallbackWrapper(
Glenn Kastend217a8c2011-06-01 15:20:35 -07002451 int event, void *cookie, void *info) {
Steve Block3856b092011-10-20 11:56:00 +01002452 //ALOGV("callbackwrapper");
Marco Nelissen6b74d672012-02-28 16:07:44 -08002453 CallbackData *data = (CallbackData*)cookie;
Andy Hungd1c74342015-07-07 16:54:23 -07002454 // lock to ensure we aren't caught in the middle of a track switch.
Marco Nelissen6b74d672012-02-28 16:07:44 -08002455 data->lock();
2456 AudioOutput *me = data->getOutput();
Andreas Huber20111aa2009-07-14 16:56:47 -07002457 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002458 if (me == NULL) {
2459 // no output set, likely because the track was scheduled to be reused
2460 // by another player, but the format turned out to be incompatible.
2461 data->unlock();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002462 if (buffer != NULL) {
2463 buffer->size = 0;
2464 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08002465 return;
2466 }
Andreas Huber20111aa2009-07-14 16:56:47 -07002467
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002468 switch(event) {
2469 case AudioTrack::EVENT_MORE_DATA: {
2470 size_t actualSize = (*me->mCallback)(
2471 me, buffer->raw, buffer->size, me->mCallbackCookie,
2472 CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002473
Andy Hung719b46b2015-05-31 22:18:25 -07002474 // Log when no data is returned from the callback.
2475 // (1) We may have no data (especially with network streaming sources).
2476 // (2) We may have reached the EOS and the audio track is not stopped yet.
2477 // Note that AwesomePlayer/AudioPlayer will only return zero size when it reaches the EOS.
2478 // NuPlayerRenderer will return zero when it doesn't have data (it doesn't block to fill).
2479 //
2480 // This is a benign busy-wait, with the next data request generated 10 ms or more later;
2481 // nevertheless for power reasons, we don't want to see too many of these.
Andreas Huber2e8ffaf2010-02-18 16:45:13 -08002482
Andy Hung719b46b2015-05-31 22:18:25 -07002483 ALOGV_IF(actualSize == 0 && buffer->size > 0, "callbackwrapper: empty buffer returned");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002484
2485 buffer->size = actualSize;
2486 } break;
2487
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002488 case AudioTrack::EVENT_STREAM_END:
Andy Hung719b46b2015-05-31 22:18:25 -07002489 // currently only occurs for offloaded callbacks
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002490 ALOGV("callbackwrapper: deliver EVENT_STREAM_END");
2491 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2492 me->mCallbackCookie, CB_EVENT_STREAM_END);
2493 break;
2494
2495 case AudioTrack::EVENT_NEW_IAUDIOTRACK :
2496 ALOGV("callbackwrapper: deliver EVENT_TEAR_DOWN");
2497 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2498 me->mCallbackCookie, CB_EVENT_TEAR_DOWN);
2499 break;
2500
Glenn Kasten421743b2015-06-01 08:18:08 -07002501 case AudioTrack::EVENT_UNDERRUN:
Andy Hung719b46b2015-05-31 22:18:25 -07002502 // This occurs when there is no data available, typically
Glenn Kasten421743b2015-06-01 08:18:08 -07002503 // when there is a failure to supply data to the AudioTrack. It can also
2504 // occur in non-offloaded mode when the audio device comes out of standby.
2505 //
Andy Hung719b46b2015-05-31 22:18:25 -07002506 // If an AudioTrack underruns it outputs silence. Since this happens suddenly
2507 // it may sound like an audible pop or glitch.
2508 //
2509 // The underrun event is sent once per track underrun; the condition is reset
2510 // when more data is sent to the AudioTrack.
Eric Laurente93cc032016-05-05 10:15:10 -07002511 ALOGD("callbackwrapper: EVENT_UNDERRUN (discarded)");
Glenn Kasten421743b2015-06-01 08:18:08 -07002512 break;
2513
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002514 default:
2515 ALOGE("received unknown event type: %d inside CallbackWrapper !", event);
Andreas Huber51c1e0e2011-04-04 11:43:40 -07002516 }
2517
Marco Nelissen6b74d672012-02-28 16:07:44 -08002518 data->unlock();
Andreas Huber20111aa2009-07-14 16:56:47 -07002519}
2520
Glenn Kastend848eb42016-03-08 13:42:11 -08002521audio_session_t MediaPlayerService::AudioOutput::getSessionId() const
Eric Laurent8c563ed2010-10-07 18:23:03 -07002522{
Andy Hungd1c74342015-07-07 16:54:23 -07002523 Mutex::Autolock lock(mLock);
Eric Laurent8c563ed2010-10-07 18:23:03 -07002524 return mSessionId;
2525}
2526
Eric Laurent6f59db12013-07-26 17:16:50 -07002527uint32_t MediaPlayerService::AudioOutput::getSampleRate() const
2528{
Andy Hungd1c74342015-07-07 16:54:23 -07002529 Mutex::Autolock lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -07002530 if (mTrack == 0) return 0;
2531 return mTrack->getSampleRate();
2532}
2533
Andy Hungf2c87b32016-04-07 19:49:29 -07002534int64_t MediaPlayerService::AudioOutput::getBufferDurationInUs() const
2535{
2536 Mutex::Autolock lock(mLock);
2537 if (mTrack == 0) {
2538 return 0;
2539 }
2540 int64_t duration;
2541 if (mTrack->getBufferDurationInUs(&duration) != OK) {
2542 return 0;
2543 }
2544 return duration;
2545}
2546
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002547////////////////////////////////////////////////////////////////////////////////
2548
2549struct CallbackThread : public Thread {
2550 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
2551 MediaPlayerBase::AudioSink::AudioCallback cb,
2552 void *cookie);
2553
2554protected:
2555 virtual ~CallbackThread();
2556
2557 virtual bool threadLoop();
2558
2559private:
2560 wp<MediaPlayerBase::AudioSink> mSink;
2561 MediaPlayerBase::AudioSink::AudioCallback mCallback;
2562 void *mCookie;
2563 void *mBuffer;
2564 size_t mBufferSize;
2565
2566 CallbackThread(const CallbackThread &);
2567 CallbackThread &operator=(const CallbackThread &);
2568};
2569
2570CallbackThread::CallbackThread(
2571 const wp<MediaPlayerBase::AudioSink> &sink,
2572 MediaPlayerBase::AudioSink::AudioCallback cb,
2573 void *cookie)
2574 : mSink(sink),
2575 mCallback(cb),
2576 mCookie(cookie),
2577 mBuffer(NULL),
2578 mBufferSize(0) {
2579}
2580
2581CallbackThread::~CallbackThread() {
2582 if (mBuffer) {
2583 free(mBuffer);
2584 mBuffer = NULL;
2585 }
2586}
2587
2588bool CallbackThread::threadLoop() {
2589 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
2590 if (sink == NULL) {
2591 return false;
2592 }
2593
2594 if (mBuffer == NULL) {
2595 mBufferSize = sink->bufferSize();
2596 mBuffer = malloc(mBufferSize);
2597 }
2598
2599 size_t actualSize =
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002600 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie,
2601 MediaPlayerBase::AudioSink::CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002602
2603 if (actualSize > 0) {
2604 sink->write(mBuffer, actualSize);
Andy Hunga31335a2014-08-20 17:37:59 -07002605 // Could return false on sink->write() error or short count.
2606 // Not necessarily appropriate but would work for AudioCache behavior.
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002607 }
2608
2609 return true;
2610}
2611
2612////////////////////////////////////////////////////////////////////////////////
2613
Chong Zhange5b9b692017-05-11 11:44:56 -07002614void MediaPlayerService::addBatteryData(uint32_t params) {
2615 mBatteryTracker.addBatteryData(params);
2616}
2617
2618status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
2619 return mBatteryTracker.pullBatteryData(reply);
2620}
2621
2622MediaPlayerService::BatteryTracker::BatteryTracker() {
2623 mBatteryAudio.refCount = 0;
2624 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2625 mBatteryAudio.deviceOn[i] = 0;
2626 mBatteryAudio.lastTime[i] = 0;
2627 mBatteryAudio.totalTime[i] = 0;
2628 }
2629 // speaker is on by default
2630 mBatteryAudio.deviceOn[SPEAKER] = 1;
2631
2632 // reset battery stats
2633 // if the mediaserver has crashed, battery stats could be left
2634 // in bad state, reset the state upon service start.
2635 BatteryNotifier::getInstance().noteResetVideo();
2636}
2637
2638void MediaPlayerService::BatteryTracker::addBatteryData(uint32_t params)
Gloria Wang7cf180c2011-02-19 18:37:57 -08002639{
2640 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002641
2642 int32_t time = systemTime() / 1000000L;
2643
2644 // change audio output devices. This notification comes from AudioFlinger
2645 if ((params & kBatteryDataSpeakerOn)
2646 || (params & kBatteryDataOtherAudioDeviceOn)) {
2647
2648 int deviceOn[NUM_AUDIO_DEVICES];
2649 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2650 deviceOn[i] = 0;
2651 }
2652
2653 if ((params & kBatteryDataSpeakerOn)
2654 && (params & kBatteryDataOtherAudioDeviceOn)) {
2655 deviceOn[SPEAKER_AND_OTHER] = 1;
2656 } else if (params & kBatteryDataSpeakerOn) {
2657 deviceOn[SPEAKER] = 1;
2658 } else {
2659 deviceOn[OTHER_AUDIO_DEVICE] = 1;
2660 }
2661
2662 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2663 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
2664
2665 if (mBatteryAudio.refCount > 0) { // if playing audio
2666 if (!deviceOn[i]) {
2667 mBatteryAudio.lastTime[i] += time;
2668 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2669 mBatteryAudio.lastTime[i] = 0;
2670 } else {
2671 mBatteryAudio.lastTime[i] = 0 - time;
2672 }
2673 }
2674
2675 mBatteryAudio.deviceOn[i] = deviceOn[i];
2676 }
2677 }
2678 return;
2679 }
2680
Marco Nelissenb7848f12014-12-04 08:57:56 -08002681 // an audio stream is started
Gloria Wang9ee159b2011-02-24 14:51:45 -08002682 if (params & kBatteryDataAudioFlingerStart) {
2683 // record the start time only if currently no other audio
2684 // is being played
2685 if (mBatteryAudio.refCount == 0) {
2686 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2687 if (mBatteryAudio.deviceOn[i]) {
2688 mBatteryAudio.lastTime[i] -= time;
2689 }
2690 }
2691 }
2692
2693 mBatteryAudio.refCount ++;
2694 return;
2695
2696 } else if (params & kBatteryDataAudioFlingerStop) {
2697 if (mBatteryAudio.refCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002698 ALOGW("Battery track warning: refCount is <= 0");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002699 return;
2700 }
2701
2702 // record the stop time only if currently this is the only
2703 // audio being played
2704 if (mBatteryAudio.refCount == 1) {
2705 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2706 if (mBatteryAudio.deviceOn[i]) {
2707 mBatteryAudio.lastTime[i] += time;
2708 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2709 mBatteryAudio.lastTime[i] = 0;
2710 }
2711 }
2712 }
2713
2714 mBatteryAudio.refCount --;
2715 return;
2716 }
2717
Andy Hung1afd0982016-11-08 16:13:44 -08002718 uid_t uid = IPCThreadState::self()->getCallingUid();
Gloria Wang7cf180c2011-02-19 18:37:57 -08002719 if (uid == AID_MEDIA) {
2720 return;
2721 }
2722 int index = mBatteryData.indexOfKey(uid);
Gloria Wang7cf180c2011-02-19 18:37:57 -08002723
2724 if (index < 0) { // create a new entry for this UID
2725 BatteryUsageInfo info;
2726 info.audioTotalTime = 0;
2727 info.videoTotalTime = 0;
2728 info.audioLastTime = 0;
2729 info.videoLastTime = 0;
2730 info.refCount = 0;
2731
Gloria Wang9ee159b2011-02-24 14:51:45 -08002732 if (mBatteryData.add(uid, info) == NO_MEMORY) {
Steve Block29357bc2012-01-06 19:20:56 +00002733 ALOGE("Battery track error: no memory for new app");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002734 return;
2735 }
Gloria Wang7cf180c2011-02-19 18:37:57 -08002736 }
2737
2738 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
2739
2740 if (params & kBatteryDataCodecStarted) {
2741 if (params & kBatteryDataTrackAudio) {
2742 info.audioLastTime -= time;
2743 info.refCount ++;
2744 }
2745 if (params & kBatteryDataTrackVideo) {
2746 info.videoLastTime -= time;
2747 info.refCount ++;
2748 }
2749 } else {
2750 if (info.refCount == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002751 ALOGW("Battery track warning: refCount is already 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002752 return;
2753 } else if (info.refCount < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00002754 ALOGE("Battery track error: refCount < 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002755 mBatteryData.removeItem(uid);
2756 return;
2757 }
2758
2759 if (params & kBatteryDataTrackAudio) {
2760 info.audioLastTime += time;
2761 info.refCount --;
2762 }
2763 if (params & kBatteryDataTrackVideo) {
2764 info.videoLastTime += time;
2765 info.refCount --;
2766 }
2767
2768 // no stream is being played by this UID
2769 if (info.refCount == 0) {
2770 info.audioTotalTime += info.audioLastTime;
2771 info.audioLastTime = 0;
2772 info.videoTotalTime += info.videoLastTime;
2773 info.videoLastTime = 0;
2774 }
2775 }
2776}
2777
Chong Zhange5b9b692017-05-11 11:44:56 -07002778status_t MediaPlayerService::BatteryTracker::pullBatteryData(Parcel* reply) {
Gloria Wang7cf180c2011-02-19 18:37:57 -08002779 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002780
2781 // audio output devices usage
2782 int32_t time = systemTime() / 1000000L; //in ms
2783 int32_t totalTime;
2784
2785 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2786 totalTime = mBatteryAudio.totalTime[i];
2787
2788 if (mBatteryAudio.deviceOn[i]
2789 && (mBatteryAudio.lastTime[i] != 0)) {
2790 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
2791 totalTime += tmpTime;
2792 }
2793
2794 reply->writeInt32(totalTime);
2795 // reset the total time
2796 mBatteryAudio.totalTime[i] = 0;
2797 }
2798
2799 // codec usage
Gloria Wang7cf180c2011-02-19 18:37:57 -08002800 BatteryUsageInfo info;
2801 int size = mBatteryData.size();
2802
2803 reply->writeInt32(size);
2804 int i = 0;
2805
2806 while (i < size) {
2807 info = mBatteryData.valueAt(i);
2808
2809 reply->writeInt32(mBatteryData.keyAt(i)); //UID
2810 reply->writeInt32(info.audioTotalTime);
2811 reply->writeInt32(info.videoTotalTime);
2812
2813 info.audioTotalTime = 0;
2814 info.videoTotalTime = 0;
2815
2816 // remove the UID entry where no stream is being played
2817 if (info.refCount <= 0) {
2818 mBatteryData.removeItemsAt(i);
2819 size --;
2820 i --;
2821 }
2822 i++;
2823 }
2824 return NO_ERROR;
2825}
nikoa64c8c72009-07-20 15:07:26 -07002826} // namespace android