blob: 66185d58fd22be787685ca1f55378aa6eb55780f [file] [log] [blame]
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001/*
2**
3** Copyright 2008, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18// Proxy for media player implementations
19
20//#define LOG_NDEBUG 0
21#define LOG_TAG "MediaPlayerService"
22#include <utils/Log.h>
23
24#include <sys/types.h>
25#include <sys/stat.h>
Gloria Wang7cf180c2011-02-19 18:37:57 -080026#include <sys/time.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080027#include <dirent.h>
28#include <unistd.h>
29
30#include <string.h>
Mathias Agopian6f74b0c2009-06-03 17:32:49 -070031
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080032#include <cutils/atomic.h>
Nicolas Catania14d27472009-07-13 14:37:49 -070033#include <cutils/properties.h> // for property_get
Mathias Agopian6f74b0c2009-06-03 17:32:49 -070034
35#include <utils/misc.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080036
Mathias Agopian75624082009-05-19 19:08:10 -070037#include <binder/IPCThreadState.h>
38#include <binder/IServiceManager.h>
39#include <binder/MemoryHeapBase.h>
40#include <binder/MemoryBase.h>
Mathias Agopianb1e7cd12013-02-14 17:11:27 -080041#include <gui/Surface.h>
Nicolas Catania1d187f12009-05-12 23:25:55 -070042#include <utils/Errors.h> // for status_t
43#include <utils/String8.h>
Marco Nelissen10dbb8e2009-09-20 10:42:13 -070044#include <utils/SystemClock.h>
Lajos Molnar06ad1522014-08-28 07:27:44 -070045#include <utils/Timers.h>
Nicolas Catania1d187f12009-05-12 23:25:55 -070046#include <utils/Vector.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080047
Eric Laurent43562692015-07-15 16:49:07 -070048#include <media/AudioPolicyHelper.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080049#include <media/IMediaHTTPService.h>
Jeff Brown2013a542012-09-04 21:38:42 -070050#include <media/IRemoteDisplay.h>
51#include <media/IRemoteDisplayClient.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080052#include <media/MediaPlayerInterface.h>
53#include <media/mediarecorder.h>
54#include <media/MediaMetadataRetrieverInterface.h>
nikoa64c8c72009-07-20 15:07:26 -070055#include <media/Metadata.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080056#include <media/AudioTrack.h>
James Dong8635b7b2011-03-14 17:01:38 -070057#include <media/MemoryLeakTrackUtil.h>
Lajos Molnar1381d4b2014-08-07 15:18:35 -070058#include <media/stagefright/MediaCodecList.h>
Eric Laurent9cb839a2011-09-27 09:48:56 -070059#include <media/stagefright/MediaErrors.h>
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +010060#include <media/stagefright/AudioPlayer.h>
Marco Nelissen83b0fd92015-09-16 13:48:07 -070061#include <media/stagefright/Utils.h>
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +010062#include <media/stagefright/foundation/ADebug.h>
Marco Nelissenf09611f2015-02-13 14:12:42 -080063#include <media/stagefright/foundation/ALooperRoster.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070064#include <mediautils/BatteryNotifier.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080065
Dima Zavin64760242011-05-11 14:15:23 -070066#include <system/audio.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070067
Gloria Wang7cf180c2011-02-19 18:37:57 -080068#include <private/android_filesystem_config.h>
69
James Dong559bf282012-03-28 10:29:14 -070070#include "ActivityManager.h"
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080071#include "MediaRecorderClient.h"
72#include "MediaPlayerService.h"
73#include "MetadataRetrieverClient.h"
John Grossman44a7e422012-06-21 17:29:24 -070074#include "MediaPlayerFactory.h"
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080075
Nicolas Catania14d27472009-07-13 14:37:49 -070076#include "TestPlayerStub.h"
Andreas Huber20111aa2009-07-14 16:56:47 -070077#include "StagefrightPlayer.h"
Andreas Huberf9334412010-12-15 15:17:42 -080078#include "nuplayer/NuPlayerDriver.h"
Andreas Huber20111aa2009-07-14 16:56:47 -070079
Andreas Huber20111aa2009-07-14 16:56:47 -070080#include <OMX.h>
Nicolas Catania14d27472009-07-13 14:37:49 -070081
Andreas Hubered3e3e02012-03-26 11:13:27 -070082#include "Crypto.h"
Jeff Tinkercc82dc62013-02-08 10:18:35 -080083#include "Drm.h"
Andreas Huber59451f82012-09-18 10:36:32 -070084#include "HDCP.h"
Andreas Huberb7319a72013-05-29 14:20:52 -070085#include "HTTPBase.h"
Andreas Huber35213f12012-08-29 11:41:50 -070086#include "RemoteDisplay.h"
Andreas Hubered3e3e02012-03-26 11:13:27 -070087
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070088namespace {
nikoa64c8c72009-07-20 15:07:26 -070089using android::media::Metadata;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070090using android::status_t;
91using android::OK;
92using android::BAD_VALUE;
93using android::NOT_ENOUGH_DATA;
94using android::Parcel;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070095
96// Max number of entries in the filter.
97const int kMaxFilterSize = 64; // I pulled that out of thin air.
98
nikoa64c8c72009-07-20 15:07:26 -070099// FIXME: Move all the metadata related function in the Metadata.cpp
nikod608a812009-07-16 16:39:53 -0700100
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700101
102// Unmarshall a filter from a Parcel.
103// Filter format in a parcel:
104//
105// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
106// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
107// | number of entries (n) |
108// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
109// | metadata type 1 |
110// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
111// | metadata type 2 |
112// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
113// ....
114// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
115// | metadata type n |
116// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
117//
118// @param p Parcel that should start with a filter.
119// @param[out] filter On exit contains the list of metadata type to be
120// filtered.
121// @param[out] status On exit contains the status code to be returned.
122// @return true if the parcel starts with a valid filter.
123bool unmarshallFilter(const Parcel& p,
nikoa64c8c72009-07-20 15:07:26 -0700124 Metadata::Filter *filter,
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700125 status_t *status)
126{
Nicolas Catania48290382009-07-10 13:53:06 -0700127 int32_t val;
128 if (p.readInt32(&val) != OK)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700129 {
Steve Block29357bc2012-01-06 19:20:56 +0000130 ALOGE("Failed to read filter's length");
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700131 *status = NOT_ENOUGH_DATA;
132 return false;
133 }
134
Nicolas Catania48290382009-07-10 13:53:06 -0700135 if( val > kMaxFilterSize || val < 0)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700136 {
Steve Block29357bc2012-01-06 19:20:56 +0000137 ALOGE("Invalid filter len %d", val);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700138 *status = BAD_VALUE;
139 return false;
140 }
141
Nicolas Catania48290382009-07-10 13:53:06 -0700142 const size_t num = val;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700143
144 filter->clear();
Nicolas Catania48290382009-07-10 13:53:06 -0700145 filter->setCapacity(num);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700146
nikoa64c8c72009-07-20 15:07:26 -0700147 size_t size = num * sizeof(Metadata::Type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700148
Nicolas Catania48290382009-07-10 13:53:06 -0700149
150 if (p.dataAvail() < size)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700151 {
Steve Block29357bc2012-01-06 19:20:56 +0000152 ALOGE("Filter too short expected %d but got %d", size, p.dataAvail());
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700153 *status = NOT_ENOUGH_DATA;
154 return false;
155 }
156
nikoa64c8c72009-07-20 15:07:26 -0700157 const Metadata::Type *data =
158 static_cast<const Metadata::Type*>(p.readInplace(size));
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700159
Nicolas Catania48290382009-07-10 13:53:06 -0700160 if (NULL == data)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700161 {
Steve Block29357bc2012-01-06 19:20:56 +0000162 ALOGE("Filter had no data");
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700163 *status = BAD_VALUE;
164 return false;
165 }
166
167 // TODO: The stl impl of vector would be more efficient here
168 // because it degenerates into a memcpy on pod types. Try to
169 // replace later or use stl::set.
Nicolas Catania48290382009-07-10 13:53:06 -0700170 for (size_t i = 0; i < num; ++i)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700171 {
Nicolas Catania48290382009-07-10 13:53:06 -0700172 filter->add(*data);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700173 ++data;
174 }
175 *status = OK;
176 return true;
177}
178
Nicolas Catania48290382009-07-10 13:53:06 -0700179// @param filter Of metadata type.
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700180// @param val To be searched.
181// @return true if a match was found.
nikoa64c8c72009-07-20 15:07:26 -0700182bool findMetadata(const Metadata::Filter& filter, const int32_t val)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700183{
184 // Deal with empty and ANY right away
185 if (filter.isEmpty()) return false;
nikoa64c8c72009-07-20 15:07:26 -0700186 if (filter[0] == Metadata::kAny) return true;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700187
Nicolas Catania48290382009-07-10 13:53:06 -0700188 return filter.indexOf(val) >= 0;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700189}
190
191} // anonymous namespace
192
193
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700194namespace {
195using android::Parcel;
196using android::String16;
197
198// marshalling tag indicating flattened utf16 tags
199// keep in sync with frameworks/base/media/java/android/media/AudioAttributes.java
200const int32_t kAudioAttributesMarshallTagFlattenTags = 1;
201
202// Audio attributes format in a parcel:
203//
204// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
205// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
206// | usage |
207// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
208// | content_type |
209// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Hyejin Kim4f418f92014-09-05 15:50:03 +0900210// | source |
211// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700212// | flags |
213// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
214// | kAudioAttributesMarshallTagFlattenTags | // ignore tags if not found
215// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
216// | flattened tags in UTF16 |
217// | ... |
218// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
219//
220// @param p Parcel that contains audio attributes.
221// @param[out] attributes On exit points to an initialized audio_attributes_t structure
222// @param[out] status On exit contains the status code to be returned.
223void unmarshallAudioAttributes(const Parcel& parcel, audio_attributes_t *attributes)
224{
225 attributes->usage = (audio_usage_t) parcel.readInt32();
226 attributes->content_type = (audio_content_type_t) parcel.readInt32();
Hyejin Kim4f418f92014-09-05 15:50:03 +0900227 attributes->source = (audio_source_t) parcel.readInt32();
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700228 attributes->flags = (audio_flags_mask_t) parcel.readInt32();
229 const bool hasFlattenedTag = (parcel.readInt32() == kAudioAttributesMarshallTagFlattenTags);
230 if (hasFlattenedTag) {
231 // the tags are UTF16, convert to UTF8
232 String16 tags = parcel.readString16();
233 ssize_t realTagSize = utf16_to_utf8_length(tags.string(), tags.size());
234 if (realTagSize <= 0) {
235 strcpy(attributes->tags, "");
236 } else {
237 // copy the flattened string into the attributes as the destination for the conversion:
238 // copying array size -1, array for tags was calloc'd, no need to NULL-terminate it
239 size_t tagSize = realTagSize > AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 ?
240 AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 : realTagSize;
241 utf16_to_utf8(tags.string(), tagSize, attributes->tags);
242 }
243 } else {
244 ALOGE("unmarshallAudioAttributes() received unflattened tags, ignoring tag values");
245 strcpy(attributes->tags, "");
246 }
247}
248} // anonymous namespace
249
250
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800251namespace android {
252
Marco Nelissenf09611f2015-02-13 14:12:42 -0800253extern ALooperRoster gLooperRoster;
254
255
Dave Burked681bbb2011-08-30 14:39:17 +0100256static bool checkPermission(const char* permissionString) {
Dave Burked681bbb2011-08-30 14:39:17 +0100257 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
258 bool ok = checkCallingPermission(String16(permissionString));
Steve Block29357bc2012-01-06 19:20:56 +0000259 if (!ok) ALOGE("Request requires %s", permissionString);
Dave Burked681bbb2011-08-30 14:39:17 +0100260 return ok;
261}
262
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800263// TODO: Find real cause of Audio/Video delay in PV framework and remove this workaround
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800264/* static */ int MediaPlayerService::AudioOutput::mMinBufferCount = 4;
265/* static */ bool MediaPlayerService::AudioOutput::mIsOnEmulator = false;
266
267void MediaPlayerService::instantiate() {
268 defaultServiceManager()->addService(
269 String16("media.player"), new MediaPlayerService());
270}
271
272MediaPlayerService::MediaPlayerService()
273{
Steve Block3856b092011-10-20 11:56:00 +0100274 ALOGV("MediaPlayerService created");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800275 mNextConnId = 1;
Gloria Wang9ee159b2011-02-24 14:51:45 -0800276
277 mBatteryAudio.refCount = 0;
278 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
279 mBatteryAudio.deviceOn[i] = 0;
280 mBatteryAudio.lastTime[i] = 0;
281 mBatteryAudio.totalTime[i] = 0;
282 }
283 // speaker is on by default
284 mBatteryAudio.deviceOn[SPEAKER] = 1;
John Grossman44a7e422012-06-21 17:29:24 -0700285
Chong Zhang0b30fd42014-07-23 14:46:05 -0700286 // reset battery stats
287 // if the mediaserver has crashed, battery stats could be left
288 // in bad state, reset the state upon service start.
Wei Jia3f273d12015-11-24 09:06:49 -0800289 BatteryNotifier::getInstance().noteResetVideo();
Chong Zhang0b30fd42014-07-23 14:46:05 -0700290
John Grossman44a7e422012-06-21 17:29:24 -0700291 MediaPlayerFactory::registerBuiltinFactories();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800292}
293
294MediaPlayerService::~MediaPlayerService()
295{
Steve Block3856b092011-10-20 11:56:00 +0100296 ALOGV("MediaPlayerService destroyed");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800297}
298
Svet Ganovbe71aa22015-04-28 12:06:02 -0700299sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(const String16 &opPackageName)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800300{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800301 pid_t pid = IPCThreadState::self()->getCallingPid();
Svet Ganovbe71aa22015-04-28 12:06:02 -0700302 sp<MediaRecorderClient> recorder = new MediaRecorderClient(this, pid, opPackageName);
Gloria Wangdac6a312009-10-29 15:46:37 -0700303 wp<MediaRecorderClient> w = recorder;
304 Mutex::Autolock lock(mLock);
305 mMediaRecorderClients.add(w);
Steve Block3856b092011-10-20 11:56:00 +0100306 ALOGV("Create new media recorder client from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800307 return recorder;
308}
309
Gloria Wangdac6a312009-10-29 15:46:37 -0700310void MediaPlayerService::removeMediaRecorderClient(wp<MediaRecorderClient> client)
311{
312 Mutex::Autolock lock(mLock);
313 mMediaRecorderClients.remove(client);
Steve Block3856b092011-10-20 11:56:00 +0100314 ALOGV("Delete media recorder client");
Gloria Wangdac6a312009-10-29 15:46:37 -0700315}
316
Glenn Kastenf37971f2012-02-03 11:06:53 -0800317sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800318{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800319 pid_t pid = IPCThreadState::self()->getCallingPid();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800320 sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
Steve Block3856b092011-10-20 11:56:00 +0100321 ALOGV("Create new media retriever from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800322 return retriever;
323}
324
Glenn Kastenf37971f2012-02-03 11:06:53 -0800325sp<IMediaPlayer> MediaPlayerService::create(const sp<IMediaPlayerClient>& client,
Dave Burked681bbb2011-08-30 14:39:17 +0100326 int audioSessionId)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800327{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800328 pid_t pid = IPCThreadState::self()->getCallingPid();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800329 int32_t connId = android_atomic_inc(&mNextConnId);
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700330
331 sp<Client> c = new Client(
332 this, pid, connId, client, audioSessionId,
333 IPCThreadState::self()->getCallingUid());
334
Steve Block3856b092011-10-20 11:56:00 +0100335 ALOGV("Create new client(%d) from pid %d, uid %d, ", connId, pid,
Dave Burked681bbb2011-08-30 14:39:17 +0100336 IPCThreadState::self()->getCallingUid());
337
338 wp<Client> w = c;
339 {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800340 Mutex::Autolock lock(mLock);
341 mClients.add(w);
342 }
Andreas Hubere2b10282010-11-23 11:41:34 -0800343 return c;
344}
345
Lajos Molnar1381d4b2014-08-07 15:18:35 -0700346sp<IMediaCodecList> MediaPlayerService::getCodecList() const {
347 return MediaCodecList::getLocalInstance();
348}
349
Andreas Hubered3e3e02012-03-26 11:13:27 -0700350sp<ICrypto> MediaPlayerService::makeCrypto() {
Andreas Huber1bd139a2012-04-03 14:19:20 -0700351 return new Crypto;
Andreas Hubered3e3e02012-03-26 11:13:27 -0700352}
353
Jeff Tinkercc82dc62013-02-08 10:18:35 -0800354sp<IDrm> MediaPlayerService::makeDrm() {
355 return new Drm;
356}
357
Andreas Huber279dcd82013-01-30 10:41:25 -0800358sp<IHDCP> MediaPlayerService::makeHDCP(bool createEncryptionModule) {
359 return new HDCP(createEncryptionModule);
Andreas Huber59451f82012-09-18 10:36:32 -0700360}
361
Jeff Brown2013a542012-09-04 21:38:42 -0700362sp<IRemoteDisplay> MediaPlayerService::listenForRemoteDisplay(
Svet Ganovbe71aa22015-04-28 12:06:02 -0700363 const String16 &opPackageName,
Jeff Brown2013a542012-09-04 21:38:42 -0700364 const sp<IRemoteDisplayClient>& client, const String8& iface) {
Jeff Brownaba33d52012-09-07 17:38:58 -0700365 if (!checkPermission("android.permission.CONTROL_WIFI_DISPLAY")) {
366 return NULL;
367 }
368
Svet Ganovbe71aa22015-04-28 12:06:02 -0700369 return new RemoteDisplay(opPackageName, client, iface.string());
Jeff Brown2013a542012-09-04 21:38:42 -0700370}
371
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800372status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
373{
374 const size_t SIZE = 256;
375 char buffer[SIZE];
376 String8 result;
377
378 result.append(" AudioOutput\n");
379 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n",
380 mStreamType, mLeftVolume, mRightVolume);
381 result.append(buffer);
382 snprintf(buffer, 255, " msec per frame(%f), latency (%d)\n",
Eric Laurentdb354e52012-03-05 17:27:11 -0800383 mMsecsPerFrame, (mTrack != 0) ? mTrack->latency() : -1);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800384 result.append(buffer);
Eric Laurent2beeb502010-07-16 07:43:46 -0700385 snprintf(buffer, 255, " aux effect id(%d), send level (%f)\n",
386 mAuxEffectId, mSendLevel);
387 result.append(buffer);
388
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800389 ::write(fd, result.string(), result.size());
390 if (mTrack != 0) {
391 mTrack->dump(fd, args);
392 }
393 return NO_ERROR;
394}
395
Lajos Molnar6d339f12015-04-17 16:15:53 -0700396status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800397{
398 const size_t SIZE = 256;
399 char buffer[SIZE];
400 String8 result;
401 result.append(" Client\n");
402 snprintf(buffer, 255, " pid(%d), connId(%d), status(%d), looping(%s)\n",
403 mPid, mConnId, mStatus, mLoop?"true": "false");
404 result.append(buffer);
405 write(fd, result.string(), result.size());
Andreas Hubera0b1d4b2011-06-07 15:52:25 -0700406 if (mPlayer != NULL) {
407 mPlayer->dump(fd, args);
408 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800409 if (mAudioOutput != 0) {
410 mAudioOutput->dump(fd, args);
411 }
412 write(fd, "\n", 1);
413 return NO_ERROR;
414}
415
Marco Nelissenf09611f2015-02-13 14:12:42 -0800416/**
417 * The only arguments this understands right now are -c, -von and -voff,
418 * which are parsed by ALooperRoster::dump()
419 */
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800420status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
421{
422 const size_t SIZE = 256;
423 char buffer[SIZE];
424 String8 result;
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530425 SortedVector< sp<Client> > clients; //to serialise the mutex unlock & client destruction.
426 SortedVector< sp<MediaRecorderClient> > mediaRecorderClients;
427
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800428 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
429 snprintf(buffer, SIZE, "Permission Denial: "
430 "can't dump MediaPlayerService from pid=%d, uid=%d\n",
431 IPCThreadState::self()->getCallingPid(),
432 IPCThreadState::self()->getCallingUid());
433 result.append(buffer);
434 } else {
435 Mutex::Autolock lock(mLock);
436 for (int i = 0, n = mClients.size(); i < n; ++i) {
437 sp<Client> c = mClients[i].promote();
438 if (c != 0) c->dump(fd, args);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530439 clients.add(c);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800440 }
James Dongb9141222010-07-08 11:16:11 -0700441 if (mMediaRecorderClients.size() == 0) {
442 result.append(" No media recorder client\n\n");
443 } else {
444 for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
445 sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
James Donge579e282011-10-18 22:29:20 -0700446 if (c != 0) {
447 snprintf(buffer, 255, " MediaRecorderClient pid(%d)\n", c->mPid);
448 result.append(buffer);
449 write(fd, result.string(), result.size());
450 result = "\n";
451 c->dump(fd, args);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530452 mediaRecorderClients.add(c);
James Donge579e282011-10-18 22:29:20 -0700453 }
James Dongb9141222010-07-08 11:16:11 -0700454 }
Gloria Wangdac6a312009-10-29 15:46:37 -0700455 }
456
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800457 result.append(" Files opened and/or mapped:\n");
Marco Nelissenf09611f2015-02-13 14:12:42 -0800458 snprintf(buffer, SIZE, "/proc/%d/maps", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800459 FILE *f = fopen(buffer, "r");
460 if (f) {
461 while (!feof(f)) {
462 fgets(buffer, SIZE, f);
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700463 if (strstr(buffer, " /storage/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800464 strstr(buffer, " /system/sounds/") ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700465 strstr(buffer, " /data/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800466 strstr(buffer, " /system/media/")) {
467 result.append(" ");
468 result.append(buffer);
469 }
470 }
471 fclose(f);
472 } else {
473 result.append("couldn't open ");
474 result.append(buffer);
475 result.append("\n");
476 }
477
Marco Nelissenf09611f2015-02-13 14:12:42 -0800478 snprintf(buffer, SIZE, "/proc/%d/fd", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800479 DIR *d = opendir(buffer);
480 if (d) {
481 struct dirent *ent;
482 while((ent = readdir(d)) != NULL) {
483 if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
Marco Nelissenf09611f2015-02-13 14:12:42 -0800484 snprintf(buffer, SIZE, "/proc/%d/fd/%s", getpid(), ent->d_name);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800485 struct stat s;
486 if (lstat(buffer, &s) == 0) {
487 if ((s.st_mode & S_IFMT) == S_IFLNK) {
488 char linkto[256];
489 int len = readlink(buffer, linkto, sizeof(linkto));
490 if(len > 0) {
491 if(len > 255) {
492 linkto[252] = '.';
493 linkto[253] = '.';
494 linkto[254] = '.';
495 linkto[255] = 0;
496 } else {
497 linkto[len] = 0;
498 }
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700499 if (strstr(linkto, "/storage/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800500 strstr(linkto, "/system/sounds/") == linkto ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700501 strstr(linkto, "/data/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800502 strstr(linkto, "/system/media/") == linkto) {
503 result.append(" ");
504 result.append(buffer);
505 result.append(" -> ");
506 result.append(linkto);
507 result.append("\n");
508 }
509 }
510 } else {
511 result.append(" unexpected type for ");
512 result.append(buffer);
513 result.append("\n");
514 }
515 }
516 }
517 }
518 closedir(d);
519 } else {
520 result.append("couldn't open ");
521 result.append(buffer);
522 result.append("\n");
523 }
524
Marco Nelissenf09611f2015-02-13 14:12:42 -0800525 gLooperRoster.dump(fd, args);
526
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800527 bool dumpMem = false;
528 for (size_t i = 0; i < args.size(); i++) {
529 if (args[i] == String16("-m")) {
530 dumpMem = true;
531 }
532 }
533 if (dumpMem) {
James Dong8635b7b2011-03-14 17:01:38 -0700534 dumpMemoryAddresses(fd);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800535 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800536 }
537 write(fd, result.string(), result.size());
538 return NO_ERROR;
539}
540
541void MediaPlayerService::removeClient(wp<Client> client)
542{
543 Mutex::Autolock lock(mLock);
544 mClients.remove(client);
545}
546
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700547MediaPlayerService::Client::Client(
548 const sp<MediaPlayerService>& service, pid_t pid,
549 int32_t connId, const sp<IMediaPlayerClient>& client,
550 int audioSessionId, uid_t uid)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800551{
Steve Block3856b092011-10-20 11:56:00 +0100552 ALOGV("Client(%d) constructor", connId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800553 mPid = pid;
554 mConnId = connId;
555 mService = service;
556 mClient = client;
557 mLoop = false;
558 mStatus = NO_INIT;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700559 mAudioSessionId = audioSessionId;
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700560 mUID = uid;
John Grossmanc795b642012-02-22 15:38:35 -0800561 mRetransmitEndpointValid = false;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700562 mAudioAttributes = NULL;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700563
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800564#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000565 ALOGD("create Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800566 mAntagonizer = new Antagonizer(notify, this);
567#endif
568}
569
570MediaPlayerService::Client::~Client()
571{
Steve Block3856b092011-10-20 11:56:00 +0100572 ALOGV("Client(%d) destructor pid = %d", mConnId, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800573 mAudioOutput.clear();
574 wp<Client> client(this);
575 disconnect();
576 mService->removeClient(client);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700577 if (mAudioAttributes != NULL) {
578 free(mAudioAttributes);
579 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800580}
581
582void MediaPlayerService::Client::disconnect()
583{
Steve Block3856b092011-10-20 11:56:00 +0100584 ALOGV("disconnect(%d) from pid %d", mConnId, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800585 // grab local reference and clear main reference to prevent future
586 // access to object
587 sp<MediaPlayerBase> p;
588 {
589 Mutex::Autolock l(mLock);
590 p = mPlayer;
beanzdcfefde2012-11-05 09:51:43 +0800591 mClient.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800592 }
Andreas Huber20111aa2009-07-14 16:56:47 -0700593
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800594 mPlayer.clear();
595
596 // clear the notification to prevent callbacks to dead client
597 // and reset the player. We assume the player will serialize
598 // access to itself if necessary.
599 if (p != 0) {
600 p->setNotifyCallback(0, 0);
601#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000602 ALOGD("kill Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800603 mAntagonizer->kill();
604#endif
605 p->reset();
606 }
607
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700608 disconnectNativeWindow();
609
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800610 IPCThreadState::self()->flushCommands();
611}
612
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800613sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
614{
615 // determine if we have the right player type
616 sp<MediaPlayerBase> p = mPlayer;
617 if ((p != NULL) && (p->playerType() != playerType)) {
Steve Block3856b092011-10-20 11:56:00 +0100618 ALOGV("delete player");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800619 p.clear();
620 }
621 if (p == NULL) {
Ronghua Wu68845c12015-07-21 09:50:48 -0700622 p = MediaPlayerFactory::createPlayer(playerType, this, notify, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800623 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700624
Jason Simmonsdb29e522011-08-12 13:46:55 -0700625 if (p != NULL) {
626 p->setUID(mUID);
627 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700628
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800629 return p;
630}
631
John Grossmanc795b642012-02-22 15:38:35 -0800632sp<MediaPlayerBase> MediaPlayerService::Client::setDataSource_pre(
633 player_type playerType)
634{
635 ALOGV("player type = %d", playerType);
636
637 // create the right type of player
638 sp<MediaPlayerBase> p = createPlayer(playerType);
639 if (p == NULL) {
640 return p;
641 }
642
643 if (!p->hardwareOutput()) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -0700644 Mutex::Autolock l(mLock);
Marco Nelissend457c972014-02-11 08:47:07 -0800645 mAudioOutput = new AudioOutput(mAudioSessionId, IPCThreadState::self()->getCallingUid(),
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700646 mPid, mAudioAttributes);
John Grossmanc795b642012-02-22 15:38:35 -0800647 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
648 }
649
650 return p;
651}
652
653void MediaPlayerService::Client::setDataSource_post(
654 const sp<MediaPlayerBase>& p,
655 status_t status)
656{
657 ALOGV(" setDataSource");
658 mStatus = status;
659 if (mStatus != OK) {
660 ALOGE(" error: %d", mStatus);
661 return;
662 }
663
664 // Set the re-transmission endpoint if one was chosen.
665 if (mRetransmitEndpointValid) {
666 mStatus = p->setRetransmitEndpoint(&mRetransmitEndpoint);
667 if (mStatus != NO_ERROR) {
668 ALOGE("setRetransmitEndpoint error: %d", mStatus);
669 }
670 }
671
672 if (mStatus == OK) {
673 mPlayer = p;
674 }
675}
676
Andreas Huber2db84552010-01-28 11:19:57 -0800677status_t MediaPlayerService::Client::setDataSource(
Andreas Huber1b86fe02014-01-29 11:13:26 -0800678 const sp<IMediaHTTPService> &httpService,
679 const char *url,
680 const KeyedVector<String8, String8> *headers)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800681{
Steve Block3856b092011-10-20 11:56:00 +0100682 ALOGV("setDataSource(%s)", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800683 if (url == NULL)
684 return UNKNOWN_ERROR;
685
Dave Burked681bbb2011-08-30 14:39:17 +0100686 if ((strncmp(url, "http://", 7) == 0) ||
687 (strncmp(url, "https://", 8) == 0) ||
688 (strncmp(url, "rtsp://", 7) == 0)) {
689 if (!checkPermission("android.permission.INTERNET")) {
690 return PERMISSION_DENIED;
691 }
692 }
693
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800694 if (strncmp(url, "content://", 10) == 0) {
695 // get a filedescriptor for the content Uri and
696 // pass it to the setDataSource(fd) method
697
698 String16 url16(url);
699 int fd = android::openContentProviderFile(url16);
700 if (fd < 0)
701 {
Steve Block29357bc2012-01-06 19:20:56 +0000702 ALOGE("Couldn't open fd for %s", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800703 return UNKNOWN_ERROR;
704 }
705 setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
706 close(fd);
707 return mStatus;
708 } else {
John Grossman44a7e422012-06-21 17:29:24 -0700709 player_type playerType = MediaPlayerFactory::getPlayerType(this, url);
John Grossmanc795b642012-02-22 15:38:35 -0800710 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
711 if (p == NULL) {
712 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800713 }
714
Andreas Huber1b86fe02014-01-29 11:13:26 -0800715 setDataSource_post(p, p->setDataSource(httpService, url, headers));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800716 return mStatus;
717 }
718}
719
720status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
721{
Marco Nelissen83b0fd92015-09-16 13:48:07 -0700722 ALOGV("setDataSource fd=%d (%s), offset=%lld, length=%lld",
723 fd, nameForFd(fd).c_str(), (long long) offset, (long long) length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800724 struct stat sb;
725 int ret = fstat(fd, &sb);
726 if (ret != 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000727 ALOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800728 return UNKNOWN_ERROR;
729 }
730
Ying Wang5fde15d2015-04-20 22:13:22 -0700731 ALOGV("st_dev = %llu", static_cast<uint64_t>(sb.st_dev));
Steve Block3856b092011-10-20 11:56:00 +0100732 ALOGV("st_mode = %u", sb.st_mode);
Mark Salyzyn77342f72014-06-18 16:31:32 -0700733 ALOGV("st_uid = %lu", static_cast<unsigned long>(sb.st_uid));
734 ALOGV("st_gid = %lu", static_cast<unsigned long>(sb.st_gid));
Steve Block3856b092011-10-20 11:56:00 +0100735 ALOGV("st_size = %llu", sb.st_size);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800736
737 if (offset >= sb.st_size) {
Steve Block29357bc2012-01-06 19:20:56 +0000738 ALOGE("offset error");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800739 return UNKNOWN_ERROR;
740 }
741 if (offset + length > sb.st_size) {
742 length = sb.st_size - offset;
Steve Block3856b092011-10-20 11:56:00 +0100743 ALOGV("calculated length = %lld", length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800744 }
745
John Grossman44a7e422012-06-21 17:29:24 -0700746 player_type playerType = MediaPlayerFactory::getPlayerType(this,
747 fd,
748 offset,
749 length);
John Grossmanc795b642012-02-22 15:38:35 -0800750 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
751 if (p == NULL) {
752 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800753 }
754
755 // now set data source
John Grossmanc795b642012-02-22 15:38:35 -0800756 setDataSource_post(p, p->setDataSource(fd, offset, length));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800757 return mStatus;
758}
759
Andreas Hubere2b10282010-11-23 11:41:34 -0800760status_t MediaPlayerService::Client::setDataSource(
761 const sp<IStreamSource> &source) {
762 // create the right type of player
John Grossman44a7e422012-06-21 17:29:24 -0700763 player_type playerType = MediaPlayerFactory::getPlayerType(this, source);
John Grossmanc795b642012-02-22 15:38:35 -0800764 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
Andreas Hubere2b10282010-11-23 11:41:34 -0800765 if (p == NULL) {
766 return NO_INIT;
767 }
768
Andreas Hubere2b10282010-11-23 11:41:34 -0800769 // now set data source
John Grossmanc795b642012-02-22 15:38:35 -0800770 setDataSource_post(p, p->setDataSource(source));
Andreas Hubere2b10282010-11-23 11:41:34 -0800771 return mStatus;
772}
773
Chris Watkins99f31602015-03-20 13:06:33 -0700774status_t MediaPlayerService::Client::setDataSource(
775 const sp<IDataSource> &source) {
776 sp<DataSource> dataSource = DataSource::CreateFromIDataSource(source);
777 player_type playerType = MediaPlayerFactory::getPlayerType(this, dataSource);
778 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
779 if (p == NULL) {
780 return NO_INIT;
781 }
782 // now set data source
783 setDataSource_post(p, p->setDataSource(dataSource));
784 return mStatus;
785}
786
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700787void MediaPlayerService::Client::disconnectNativeWindow() {
788 if (mConnectedWindow != NULL) {
789 status_t err = native_window_api_disconnect(mConnectedWindow.get(),
790 NATIVE_WINDOW_API_MEDIA);
791
792 if (err != OK) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000793 ALOGW("native_window_api_disconnect returned an error: %s (%d)",
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700794 strerror(-err), err);
795 }
796 }
797 mConnectedWindow.clear();
798}
799
Glenn Kasten11731182011-02-08 17:26:17 -0800800status_t MediaPlayerService::Client::setVideoSurfaceTexture(
Andy McFadden484566c2012-12-18 09:46:54 -0800801 const sp<IGraphicBufferProducer>& bufferProducer)
Glenn Kasten11731182011-02-08 17:26:17 -0800802{
Andy McFadden484566c2012-12-18 09:46:54 -0800803 ALOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, bufferProducer.get());
Glenn Kasten11731182011-02-08 17:26:17 -0800804 sp<MediaPlayerBase> p = getPlayer();
805 if (p == 0) return UNKNOWN_ERROR;
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700806
Marco Nelissenf8880202014-11-14 07:58:25 -0800807 sp<IBinder> binder(IInterface::asBinder(bufferProducer));
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700808 if (mConnectedWindowBinder == binder) {
809 return OK;
810 }
811
812 sp<ANativeWindow> anw;
Andy McFadden484566c2012-12-18 09:46:54 -0800813 if (bufferProducer != NULL) {
Marco Nelissenee08f7e2013-09-16 13:30:01 -0700814 anw = new Surface(bufferProducer, true /* controlledByApp */);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700815 status_t err = native_window_api_connect(anw.get(),
816 NATIVE_WINDOW_API_MEDIA);
817
818 if (err != OK) {
Steve Block29357bc2012-01-06 19:20:56 +0000819 ALOGE("setVideoSurfaceTexture failed: %d", err);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700820 // Note that we must do the reset before disconnecting from the ANW.
821 // Otherwise queue/dequeue calls could be made on the disconnected
822 // ANW, which may result in errors.
823 reset();
824
825 disconnectNativeWindow();
826
827 return err;
828 }
829 }
830
Andy McFadden484566c2012-12-18 09:46:54 -0800831 // Note that we must set the player's new GraphicBufferProducer before
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700832 // disconnecting the old one. Otherwise queue/dequeue calls could be made
833 // on the disconnected ANW, which may result in errors.
Andy McFadden484566c2012-12-18 09:46:54 -0800834 status_t err = p->setVideoSurfaceTexture(bufferProducer);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700835
836 disconnectNativeWindow();
837
838 mConnectedWindow = anw;
839
840 if (err == OK) {
841 mConnectedWindowBinder = binder;
842 } else {
843 disconnectNativeWindow();
844 }
845
846 return err;
Glenn Kasten11731182011-02-08 17:26:17 -0800847}
848
Nicolas Catania1d187f12009-05-12 23:25:55 -0700849status_t MediaPlayerService::Client::invoke(const Parcel& request,
850 Parcel *reply)
851{
852 sp<MediaPlayerBase> p = getPlayer();
853 if (p == NULL) return UNKNOWN_ERROR;
854 return p->invoke(request, reply);
855}
856
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700857// This call doesn't need to access the native player.
858status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
859{
860 status_t status;
nikoa64c8c72009-07-20 15:07:26 -0700861 media::Metadata::Filter allow, drop;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700862
Nicolas Catania48290382009-07-10 13:53:06 -0700863 if (unmarshallFilter(filter, &allow, &status) &&
864 unmarshallFilter(filter, &drop, &status)) {
865 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700866
867 mMetadataAllow = allow;
868 mMetadataDrop = drop;
869 }
870 return status;
871}
872
Nicolas Catania48290382009-07-10 13:53:06 -0700873status_t MediaPlayerService::Client::getMetadata(
Mark Salyzyn77342f72014-06-18 16:31:32 -0700874 bool update_only, bool /*apply_filter*/, Parcel *reply)
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700875{
nikoa64c8c72009-07-20 15:07:26 -0700876 sp<MediaPlayerBase> player = getPlayer();
877 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania48290382009-07-10 13:53:06 -0700878
nikod608a812009-07-16 16:39:53 -0700879 status_t status;
880 // Placeholder for the return code, updated by the caller.
881 reply->writeInt32(-1);
882
nikoa64c8c72009-07-20 15:07:26 -0700883 media::Metadata::Filter ids;
Nicolas Catania48290382009-07-10 13:53:06 -0700884
885 // We don't block notifications while we fetch the data. We clear
886 // mMetadataUpdated first so we don't lose notifications happening
887 // during the rest of this call.
888 {
889 Mutex::Autolock lock(mLock);
890 if (update_only) {
nikod608a812009-07-16 16:39:53 -0700891 ids = mMetadataUpdated;
Nicolas Catania48290382009-07-10 13:53:06 -0700892 }
893 mMetadataUpdated.clear();
894 }
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700895
nikoa64c8c72009-07-20 15:07:26 -0700896 media::Metadata metadata(reply);
Nicolas Catania48290382009-07-10 13:53:06 -0700897
nikoa64c8c72009-07-20 15:07:26 -0700898 metadata.appendHeader();
899 status = player->getMetadata(ids, reply);
nikod608a812009-07-16 16:39:53 -0700900
901 if (status != OK) {
nikoa64c8c72009-07-20 15:07:26 -0700902 metadata.resetParcel();
Steve Block29357bc2012-01-06 19:20:56 +0000903 ALOGE("getMetadata failed %d", status);
nikod608a812009-07-16 16:39:53 -0700904 return status;
905 }
906
907 // FIXME: Implement filtering on the result. Not critical since
908 // filtering takes place on the update notifications already. This
909 // would be when all the metadata are fetch and a filter is set.
910
nikod608a812009-07-16 16:39:53 -0700911 // Everything is fine, update the metadata length.
nikoa64c8c72009-07-20 15:07:26 -0700912 metadata.updateLength();
nikod608a812009-07-16 16:39:53 -0700913 return OK;
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700914}
915
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800916status_t MediaPlayerService::Client::prepareAsync()
917{
Steve Block3856b092011-10-20 11:56:00 +0100918 ALOGV("[%d] prepareAsync", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800919 sp<MediaPlayerBase> p = getPlayer();
920 if (p == 0) return UNKNOWN_ERROR;
921 status_t ret = p->prepareAsync();
922#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000923 ALOGD("start Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800924 if (ret == NO_ERROR) mAntagonizer->start();
925#endif
926 return ret;
927}
928
929status_t MediaPlayerService::Client::start()
930{
Steve Block3856b092011-10-20 11:56:00 +0100931 ALOGV("[%d] start", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800932 sp<MediaPlayerBase> p = getPlayer();
933 if (p == 0) return UNKNOWN_ERROR;
934 p->setLooping(mLoop);
935 return p->start();
936}
937
938status_t MediaPlayerService::Client::stop()
939{
Steve Block3856b092011-10-20 11:56:00 +0100940 ALOGV("[%d] stop", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800941 sp<MediaPlayerBase> p = getPlayer();
942 if (p == 0) return UNKNOWN_ERROR;
943 return p->stop();
944}
945
946status_t MediaPlayerService::Client::pause()
947{
Steve Block3856b092011-10-20 11:56:00 +0100948 ALOGV("[%d] pause", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800949 sp<MediaPlayerBase> p = getPlayer();
950 if (p == 0) return UNKNOWN_ERROR;
951 return p->pause();
952}
953
954status_t MediaPlayerService::Client::isPlaying(bool* state)
955{
956 *state = false;
957 sp<MediaPlayerBase> p = getPlayer();
958 if (p == 0) return UNKNOWN_ERROR;
959 *state = p->isPlaying();
Steve Block3856b092011-10-20 11:56:00 +0100960 ALOGV("[%d] isPlaying: %d", mConnId, *state);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800961 return NO_ERROR;
962}
963
Lajos Molnar3a474aa2015-04-24 17:10:07 -0700964status_t MediaPlayerService::Client::setPlaybackSettings(const AudioPlaybackRate& rate)
Wei Jia98160162015-02-04 17:01:11 -0800965{
Lajos Molnar3a474aa2015-04-24 17:10:07 -0700966 ALOGV("[%d] setPlaybackSettings(%f, %f, %d, %d)",
967 mConnId, rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Wei Jia98160162015-02-04 17:01:11 -0800968 sp<MediaPlayerBase> p = getPlayer();
969 if (p == 0) return UNKNOWN_ERROR;
Lajos Molnar3a474aa2015-04-24 17:10:07 -0700970 return p->setPlaybackSettings(rate);
971}
972
973status_t MediaPlayerService::Client::getPlaybackSettings(AudioPlaybackRate* rate /* nonnull */)
974{
975 sp<MediaPlayerBase> p = getPlayer();
976 if (p == 0) return UNKNOWN_ERROR;
977 status_t ret = p->getPlaybackSettings(rate);
978 if (ret == NO_ERROR) {
979 ALOGV("[%d] getPlaybackSettings(%f, %f, %d, %d)",
980 mConnId, rate->mSpeed, rate->mPitch, rate->mFallbackMode, rate->mStretchMode);
981 } else {
982 ALOGV("[%d] getPlaybackSettings returned %d", mConnId, ret);
983 }
984 return ret;
985}
986
987status_t MediaPlayerService::Client::setSyncSettings(
988 const AVSyncSettings& sync, float videoFpsHint)
989{
990 ALOGV("[%d] setSyncSettings(%u, %u, %f, %f)",
991 mConnId, sync.mSource, sync.mAudioAdjustMode, sync.mTolerance, videoFpsHint);
992 sp<MediaPlayerBase> p = getPlayer();
993 if (p == 0) return UNKNOWN_ERROR;
994 return p->setSyncSettings(sync, videoFpsHint);
995}
996
997status_t MediaPlayerService::Client::getSyncSettings(
998 AVSyncSettings* sync /* nonnull */, float* videoFps /* nonnull */)
999{
1000 sp<MediaPlayerBase> p = getPlayer();
1001 if (p == 0) return UNKNOWN_ERROR;
1002 status_t ret = p->getSyncSettings(sync, videoFps);
1003 if (ret == NO_ERROR) {
1004 ALOGV("[%d] getSyncSettings(%u, %u, %f, %f)",
1005 mConnId, sync->mSource, sync->mAudioAdjustMode, sync->mTolerance, *videoFps);
1006 } else {
1007 ALOGV("[%d] getSyncSettings returned %d", mConnId, ret);
1008 }
1009 return ret;
Wei Jia98160162015-02-04 17:01:11 -08001010}
1011
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001012status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
1013{
Steve Block3856b092011-10-20 11:56:00 +01001014 ALOGV("getCurrentPosition");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001015 sp<MediaPlayerBase> p = getPlayer();
1016 if (p == 0) return UNKNOWN_ERROR;
1017 status_t ret = p->getCurrentPosition(msec);
1018 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001019 ALOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001020 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001021 ALOGE("getCurrentPosition returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001022 }
1023 return ret;
1024}
1025
1026status_t MediaPlayerService::Client::getDuration(int *msec)
1027{
Steve Block3856b092011-10-20 11:56:00 +01001028 ALOGV("getDuration");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001029 sp<MediaPlayerBase> p = getPlayer();
1030 if (p == 0) return UNKNOWN_ERROR;
1031 status_t ret = p->getDuration(msec);
1032 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001033 ALOGV("[%d] getDuration = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001034 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001035 ALOGE("getDuration returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001036 }
1037 return ret;
1038}
1039
Marco Nelissen6b74d672012-02-28 16:07:44 -08001040status_t MediaPlayerService::Client::setNextPlayer(const sp<IMediaPlayer>& player) {
1041 ALOGV("setNextPlayer");
1042 Mutex::Autolock l(mLock);
1043 sp<Client> c = static_cast<Client*>(player.get());
1044 mNextClient = c;
John Grossman5f7e55e2012-08-24 14:47:25 -07001045
1046 if (c != NULL) {
1047 if (mAudioOutput != NULL) {
1048 mAudioOutput->setNextOutput(c->mAudioOutput);
1049 } else if ((mPlayer != NULL) && !mPlayer->hardwareOutput()) {
1050 ALOGE("no current audio output");
1051 }
1052
1053 if ((mPlayer != NULL) && (mNextClient->getPlayer() != NULL)) {
1054 mPlayer->setNextPlayer(mNextClient->getPlayer());
1055 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001056 }
John Grossman5f7e55e2012-08-24 14:47:25 -07001057
Marco Nelissen6b74d672012-02-28 16:07:44 -08001058 return OK;
1059}
1060
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001061status_t MediaPlayerService::Client::seekTo(int msec)
1062{
Steve Block3856b092011-10-20 11:56:00 +01001063 ALOGV("[%d] seekTo(%d)", mConnId, msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001064 sp<MediaPlayerBase> p = getPlayer();
1065 if (p == 0) return UNKNOWN_ERROR;
1066 return p->seekTo(msec);
1067}
1068
1069status_t MediaPlayerService::Client::reset()
1070{
Steve Block3856b092011-10-20 11:56:00 +01001071 ALOGV("[%d] reset", mConnId);
John Grossmanc795b642012-02-22 15:38:35 -08001072 mRetransmitEndpointValid = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001073 sp<MediaPlayerBase> p = getPlayer();
1074 if (p == 0) return UNKNOWN_ERROR;
1075 return p->reset();
1076}
1077
Glenn Kastenfff6d712012-01-12 16:38:12 -08001078status_t MediaPlayerService::Client::setAudioStreamType(audio_stream_type_t type)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001079{
Steve Block3856b092011-10-20 11:56:00 +01001080 ALOGV("[%d] setAudioStreamType(%d)", mConnId, type);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001081 // TODO: for hardware output, call player instead
1082 Mutex::Autolock l(mLock);
1083 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1084 return NO_ERROR;
1085}
1086
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001087status_t MediaPlayerService::Client::setAudioAttributes_l(const Parcel &parcel)
1088{
1089 if (mAudioAttributes != NULL) { free(mAudioAttributes); }
1090 mAudioAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001091 if (mAudioAttributes == NULL) {
1092 return NO_MEMORY;
1093 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001094 unmarshallAudioAttributes(parcel, mAudioAttributes);
1095
1096 ALOGV("setAudioAttributes_l() usage=%d content=%d flags=0x%x tags=%s",
1097 mAudioAttributes->usage, mAudioAttributes->content_type, mAudioAttributes->flags,
1098 mAudioAttributes->tags);
1099
1100 if (mAudioOutput != 0) {
1101 mAudioOutput->setAudioAttributes(mAudioAttributes);
1102 }
1103 return NO_ERROR;
1104}
1105
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001106status_t MediaPlayerService::Client::setLooping(int loop)
1107{
Steve Block3856b092011-10-20 11:56:00 +01001108 ALOGV("[%d] setLooping(%d)", mConnId, loop);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001109 mLoop = loop;
1110 sp<MediaPlayerBase> p = getPlayer();
1111 if (p != 0) return p->setLooping(loop);
1112 return NO_ERROR;
1113}
1114
1115status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1116{
Steve Block3856b092011-10-20 11:56:00 +01001117 ALOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
John Grossman761defc2012-02-09 15:09:05 -08001118
1119 // for hardware output, call player instead
1120 sp<MediaPlayerBase> p = getPlayer();
1121 {
1122 Mutex::Autolock l(mLock);
1123 if (p != 0 && p->hardwareOutput()) {
1124 MediaPlayerHWInterface* hwp =
1125 reinterpret_cast<MediaPlayerHWInterface*>(p.get());
1126 return hwp->setVolume(leftVolume, rightVolume);
1127 } else {
1128 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1129 return NO_ERROR;
1130 }
1131 }
1132
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001133 return NO_ERROR;
1134}
1135
Eric Laurent2beeb502010-07-16 07:43:46 -07001136status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1137{
Steve Block3856b092011-10-20 11:56:00 +01001138 ALOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
Eric Laurent2beeb502010-07-16 07:43:46 -07001139 Mutex::Autolock l(mLock);
1140 if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1141 return NO_ERROR;
1142}
1143
1144status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1145{
Steve Block3856b092011-10-20 11:56:00 +01001146 ALOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
Eric Laurent2beeb502010-07-16 07:43:46 -07001147 Mutex::Autolock l(mLock);
1148 if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1149 return NO_ERROR;
1150}
Nicolas Catania48290382009-07-10 13:53:06 -07001151
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001152status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
Steve Block3856b092011-10-20 11:56:00 +01001153 ALOGV("[%d] setParameter(%d)", mConnId, key);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001154 switch (key) {
1155 case KEY_PARAMETER_AUDIO_ATTRIBUTES:
1156 {
1157 Mutex::Autolock l(mLock);
1158 return setAudioAttributes_l(request);
1159 }
1160 default:
1161 sp<MediaPlayerBase> p = getPlayer();
1162 if (p == 0) { return UNKNOWN_ERROR; }
1163 return p->setParameter(key, request);
1164 }
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001165}
1166
1167status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
Steve Block3856b092011-10-20 11:56:00 +01001168 ALOGV("[%d] getParameter(%d)", mConnId, key);
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001169 sp<MediaPlayerBase> p = getPlayer();
1170 if (p == 0) return UNKNOWN_ERROR;
1171 return p->getParameter(key, reply);
1172}
1173
John Grossmanc795b642012-02-22 15:38:35 -08001174status_t MediaPlayerService::Client::setRetransmitEndpoint(
1175 const struct sockaddr_in* endpoint) {
1176
1177 if (NULL != endpoint) {
1178 uint32_t a = ntohl(endpoint->sin_addr.s_addr);
1179 uint16_t p = ntohs(endpoint->sin_port);
1180 ALOGV("[%d] setRetransmitEndpoint(%u.%u.%u.%u:%hu)", mConnId,
1181 (a >> 24), (a >> 16) & 0xFF, (a >> 8) & 0xFF, (a & 0xFF), p);
1182 } else {
1183 ALOGV("[%d] setRetransmitEndpoint = <none>", mConnId);
1184 }
1185
1186 sp<MediaPlayerBase> p = getPlayer();
1187
1188 // Right now, the only valid time to set a retransmit endpoint is before
1189 // player selection has been made (since the presence or absence of a
1190 // retransmit endpoint is going to determine which player is selected during
1191 // setDataSource).
1192 if (p != 0) return INVALID_OPERATION;
1193
1194 if (NULL != endpoint) {
1195 mRetransmitEndpoint = *endpoint;
1196 mRetransmitEndpointValid = true;
1197 } else {
1198 mRetransmitEndpointValid = false;
1199 }
1200
1201 return NO_ERROR;
1202}
1203
John Grossman44a7e422012-06-21 17:29:24 -07001204status_t MediaPlayerService::Client::getRetransmitEndpoint(
1205 struct sockaddr_in* endpoint)
1206{
1207 if (NULL == endpoint)
1208 return BAD_VALUE;
1209
1210 sp<MediaPlayerBase> p = getPlayer();
1211
1212 if (p != NULL)
1213 return p->getRetransmitEndpoint(endpoint);
1214
1215 if (!mRetransmitEndpointValid)
1216 return NO_INIT;
1217
1218 *endpoint = mRetransmitEndpoint;
1219
1220 return NO_ERROR;
1221}
1222
Gloria Wangb483c472011-04-11 17:23:27 -07001223void MediaPlayerService::Client::notify(
1224 void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001225{
1226 Client* client = static_cast<Client*>(cookie);
James Dongb8a98252012-08-26 16:13:03 -07001227 if (client == NULL) {
1228 return;
1229 }
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001230
James Dongb8a98252012-08-26 16:13:03 -07001231 sp<IMediaPlayerClient> c;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001232 {
1233 Mutex::Autolock l(client->mLock);
James Dongb8a98252012-08-26 16:13:03 -07001234 c = client->mClient;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001235 if (msg == MEDIA_PLAYBACK_COMPLETE && client->mNextClient != NULL) {
John Grossmancb0b7552012-08-23 17:47:31 -07001236 if (client->mAudioOutput != NULL)
1237 client->mAudioOutput->switchToNextOutput();
Marco Nelissen6b74d672012-02-28 16:07:44 -08001238 client->mNextClient->start();
Wei Jia2afac0c2016-01-07 12:13:07 -08001239 if (client->mNextClient->mClient != NULL) {
1240 client->mNextClient->mClient->notify(
1241 MEDIA_INFO, MEDIA_INFO_STARTED_AS_NEXT, 0, obj);
1242 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001243 }
1244 }
1245
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001246 if (MEDIA_INFO == msg &&
Nicolas Catania48290382009-07-10 13:53:06 -07001247 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikoa64c8c72009-07-20 15:07:26 -07001248 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania48290382009-07-10 13:53:06 -07001249
1250 if(client->shouldDropMetadata(metadata_type)) {
1251 return;
1252 }
1253
1254 // Update the list of metadata that have changed. getMetadata
1255 // also access mMetadataUpdated and clears it.
1256 client->addNewMetadataUpdate(metadata_type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001257 }
James Dongb8a98252012-08-26 16:13:03 -07001258
1259 if (c != NULL) {
1260 ALOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
1261 c->notify(msg, ext1, ext2, obj);
1262 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001263}
1264
Nicolas Catania48290382009-07-10 13:53:06 -07001265
nikoa64c8c72009-07-20 15:07:26 -07001266bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001267{
Nicolas Catania48290382009-07-10 13:53:06 -07001268 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001269
Nicolas Catania48290382009-07-10 13:53:06 -07001270 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001271 return true;
1272 }
1273
Nicolas Catania48290382009-07-10 13:53:06 -07001274 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001275 return false;
Nicolas Catania48290382009-07-10 13:53:06 -07001276 } else {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001277 return true;
1278 }
1279}
1280
Nicolas Catania48290382009-07-10 13:53:06 -07001281
nikoa64c8c72009-07-20 15:07:26 -07001282void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania48290382009-07-10 13:53:06 -07001283 Mutex::Autolock lock(mLock);
1284 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1285 mMetadataUpdated.add(metadata_type);
1286 }
1287}
1288
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001289#if CALLBACK_ANTAGONIZER
1290const int Antagonizer::interval = 10000; // 10 msecs
1291
1292Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1293 mExit(false), mActive(false), mClient(client), mCb(cb)
1294{
1295 createThread(callbackThread, this);
1296}
1297
1298void Antagonizer::kill()
1299{
1300 Mutex::Autolock _l(mLock);
1301 mActive = false;
1302 mExit = true;
1303 mCondition.wait(mLock);
1304}
1305
1306int Antagonizer::callbackThread(void* user)
1307{
Steve Blockb8a80522011-12-20 16:23:08 +00001308 ALOGD("Antagonizer started");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001309 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1310 while (!p->mExit) {
1311 if (p->mActive) {
Steve Block3856b092011-10-20 11:56:00 +01001312 ALOGV("send event");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001313 p->mCb(p->mClient, 0, 0, 0);
1314 }
1315 usleep(interval);
1316 }
1317 Mutex::Autolock _l(p->mLock);
1318 p->mCondition.signal();
Steve Blockb8a80522011-12-20 16:23:08 +00001319 ALOGD("Antagonizer stopped");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001320 return 0;
1321}
1322#endif
1323
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001324#undef LOG_TAG
1325#define LOG_TAG "AudioSink"
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001326MediaPlayerService::AudioOutput::AudioOutput(int sessionId, int uid, int pid,
1327 const audio_attributes_t* attr)
Andreas Huber20111aa2009-07-14 16:56:47 -07001328 : mCallback(NULL),
Eric Laurenta514bdb2010-06-21 09:27:30 -07001329 mCallbackCookie(NULL),
Marco Nelissen6b74d672012-02-28 16:07:44 -08001330 mCallbackData(NULL),
Marco Nelissen4110c102012-03-29 09:31:28 -07001331 mBytesWritten(0),
Andy Hungd1c74342015-07-07 16:54:23 -07001332 mStreamType(AUDIO_STREAM_MUSIC),
Andy Hungd1c74342015-07-07 16:54:23 -07001333 mLeftVolume(1.0),
1334 mRightVolume(1.0),
1335 mPlaybackRate(AUDIO_PLAYBACK_RATE_DEFAULT),
1336 mSampleRateHz(0),
1337 mMsecsPerFrame(0),
1338 mFrameSize(0),
Eric Laurent1948eb32012-04-13 16:50:19 -07001339 mSessionId(sessionId),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001340 mUid(uid),
Marco Nelissend457c972014-02-11 08:47:07 -08001341 mPid(pid),
Andy Hungd1c74342015-07-07 16:54:23 -07001342 mSendLevel(0.0),
1343 mAuxEffectId(0),
1344 mFlags(AUDIO_OUTPUT_FLAG_NONE)
1345{
Steve Block3856b092011-10-20 11:56:00 +01001346 ALOGV("AudioOutput(%d)", sessionId);
Eric Laurent43562692015-07-15 16:49:07 -07001347 if (attr != NULL) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001348 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1349 if (mAttributes != NULL) {
1350 memcpy(mAttributes, attr, sizeof(audio_attributes_t));
1351 mStreamType = audio_attributes_to_stream_type(attr);
1352 }
1353 } else {
1354 mAttributes = NULL;
Eric Laurent43562692015-07-15 16:49:07 -07001355 }
1356
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001357 setMinBufferCount();
1358}
1359
1360MediaPlayerService::AudioOutput::~AudioOutput()
1361{
1362 close();
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001363 free(mAttributes);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001364 delete mCallbackData;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001365}
1366
Andy Hungd1c74342015-07-07 16:54:23 -07001367//static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001368void MediaPlayerService::AudioOutput::setMinBufferCount()
1369{
1370 char value[PROPERTY_VALUE_MAX];
1371 if (property_get("ro.kernel.qemu", value, 0)) {
1372 mIsOnEmulator = true;
1373 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1374 }
1375}
1376
Andy Hungd1c74342015-07-07 16:54:23 -07001377// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001378bool MediaPlayerService::AudioOutput::isOnEmulator()
1379{
Andy Hungd1c74342015-07-07 16:54:23 -07001380 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001381 return mIsOnEmulator;
1382}
1383
Andy Hungd1c74342015-07-07 16:54:23 -07001384// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001385int MediaPlayerService::AudioOutput::getMinBufferCount()
1386{
Andy Hungd1c74342015-07-07 16:54:23 -07001387 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001388 return mMinBufferCount;
1389}
1390
1391ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1392{
Andy Hungd1c74342015-07-07 16:54:23 -07001393 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001394 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001395 return mTrack->frameCount() * mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001396}
1397
1398ssize_t MediaPlayerService::AudioOutput::frameCount() const
1399{
Andy Hungd1c74342015-07-07 16:54:23 -07001400 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001401 if (mTrack == 0) return NO_INIT;
1402 return mTrack->frameCount();
1403}
1404
1405ssize_t MediaPlayerService::AudioOutput::channelCount() const
1406{
Andy Hungd1c74342015-07-07 16:54:23 -07001407 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001408 if (mTrack == 0) return NO_INIT;
1409 return mTrack->channelCount();
1410}
1411
1412ssize_t MediaPlayerService::AudioOutput::frameSize() const
1413{
Andy Hungd1c74342015-07-07 16:54:23 -07001414 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001415 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001416 return mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001417}
1418
1419uint32_t MediaPlayerService::AudioOutput::latency () const
1420{
Andy Hungd1c74342015-07-07 16:54:23 -07001421 Mutex::Autolock lock(mLock);
Eric Laurentdb354e52012-03-05 17:27:11 -08001422 if (mTrack == 0) return 0;
1423 return mTrack->latency();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001424}
1425
1426float MediaPlayerService::AudioOutput::msecsPerFrame() const
1427{
Andy Hungd1c74342015-07-07 16:54:23 -07001428 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001429 return mMsecsPerFrame;
1430}
1431
Marco Nelissen4110c102012-03-29 09:31:28 -07001432status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position) const
Eric Laurent342e9cf2010-01-19 17:37:09 -08001433{
Andy Hungd1c74342015-07-07 16:54:23 -07001434 Mutex::Autolock lock(mLock);
Eric Laurent342e9cf2010-01-19 17:37:09 -08001435 if (mTrack == 0) return NO_INIT;
1436 return mTrack->getPosition(position);
1437}
1438
Lajos Molnar06ad1522014-08-28 07:27:44 -07001439status_t MediaPlayerService::AudioOutput::getTimestamp(AudioTimestamp &ts) const
1440{
Andy Hungd1c74342015-07-07 16:54:23 -07001441 Mutex::Autolock lock(mLock);
Lajos Molnar06ad1522014-08-28 07:27:44 -07001442 if (mTrack == 0) return NO_INIT;
1443 return mTrack->getTimestamp(ts);
1444}
1445
Wei Jiac4ac8172015-10-21 10:35:48 -07001446// TODO: Remove unnecessary calls to getPlayedOutDurationUs()
1447// as it acquires locks and may query the audio driver.
1448//
1449// Some calls could conceivably retrieve extrapolated data instead of
1450// accessing getTimestamp() or getPosition() every time a data buffer with
1451// a media time is received.
1452//
1453// Calculate duration of played samples if played at normal rate (i.e., 1.0).
1454int64_t MediaPlayerService::AudioOutput::getPlayedOutDurationUs(int64_t nowUs) const
1455{
1456 Mutex::Autolock lock(mLock);
1457 if (mTrack == 0 || mSampleRateHz == 0) {
Wei Jia213f4902015-10-22 08:55:25 -07001458 return 0;
Wei Jiac4ac8172015-10-21 10:35:48 -07001459 }
1460
1461 uint32_t numFramesPlayed;
1462 int64_t numFramesPlayedAt;
1463 AudioTimestamp ts;
1464 static const int64_t kStaleTimestamp100ms = 100000;
1465
1466 status_t res = mTrack->getTimestamp(ts);
1467 if (res == OK) { // case 1: mixing audio tracks and offloaded tracks.
1468 numFramesPlayed = ts.mPosition;
1469 numFramesPlayedAt = ts.mTime.tv_sec * 1000000LL + ts.mTime.tv_nsec / 1000;
1470 const int64_t timestampAge = nowUs - numFramesPlayedAt;
1471 if (timestampAge > kStaleTimestamp100ms) {
1472 // This is an audio FIXME.
1473 // getTimestamp returns a timestamp which may come from audio mixing threads.
1474 // After pausing, the MixerThread may go idle, thus the mTime estimate may
1475 // become stale. Assuming that the MixerThread runs 20ms, with FastMixer at 5ms,
1476 // the max latency should be about 25ms with an average around 12ms (to be verified).
1477 // For safety we use 100ms.
1478 ALOGV("getTimestamp: returned stale timestamp nowUs(%lld) numFramesPlayedAt(%lld)",
1479 (long long)nowUs, (long long)numFramesPlayedAt);
1480 numFramesPlayedAt = nowUs - kStaleTimestamp100ms;
1481 }
1482 //ALOGD("getTimestamp: OK %d %lld", numFramesPlayed, (long long)numFramesPlayedAt);
1483 } else if (res == WOULD_BLOCK) { // case 2: transitory state on start of a new track
1484 numFramesPlayed = 0;
1485 numFramesPlayedAt = nowUs;
1486 //ALOGD("getTimestamp: WOULD_BLOCK %d %lld",
1487 // numFramesPlayed, (long long)numFramesPlayedAt);
1488 } else { // case 3: transitory at new track or audio fast tracks.
1489 res = mTrack->getPosition(&numFramesPlayed);
1490 CHECK_EQ(res, (status_t)OK);
1491 numFramesPlayedAt = nowUs;
1492 numFramesPlayedAt += 1000LL * mTrack->latency() / 2; /* XXX */
1493 //ALOGD("getPosition: %u %lld", numFramesPlayed, (long long)numFramesPlayedAt);
1494 }
1495
1496 // CHECK_EQ(numFramesPlayed & (1 << 31), 0); // can't be negative until 12.4 hrs, test
1497 // TODO: remove the (int32_t) casting below as it may overflow at 12.4 hours.
1498 int64_t durationUs = (int64_t)((int32_t)numFramesPlayed * 1000000LL / mSampleRateHz)
1499 + nowUs - numFramesPlayedAt;
1500 if (durationUs < 0) {
1501 // Occurs when numFramesPlayed position is very small and the following:
1502 // (1) In case 1, the time nowUs is computed before getTimestamp() is called and
1503 // numFramesPlayedAt is greater than nowUs by time more than numFramesPlayed.
1504 // (2) In case 3, using getPosition and adding mAudioSink->latency() to
1505 // numFramesPlayedAt, by a time amount greater than numFramesPlayed.
1506 //
1507 // Both of these are transitory conditions.
1508 ALOGV("getPlayedOutDurationUs: negative duration %lld set to zero", (long long)durationUs);
1509 durationUs = 0;
1510 }
1511 ALOGV("getPlayedOutDurationUs(%lld) nowUs(%lld) frames(%u) framesAt(%lld)",
1512 (long long)durationUs, (long long)nowUs, numFramesPlayed, (long long)numFramesPlayedAt);
1513 return durationUs;
1514}
1515
Marco Nelissen4110c102012-03-29 09:31:28 -07001516status_t MediaPlayerService::AudioOutput::getFramesWritten(uint32_t *frameswritten) const
1517{
Andy Hungd1c74342015-07-07 16:54:23 -07001518 Mutex::Autolock lock(mLock);
Marco Nelissen4110c102012-03-29 09:31:28 -07001519 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001520 *frameswritten = mBytesWritten / mFrameSize;
Marco Nelissen4110c102012-03-29 09:31:28 -07001521 return OK;
1522}
1523
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001524status_t MediaPlayerService::AudioOutput::setParameters(const String8& keyValuePairs)
1525{
Andy Hungd1c74342015-07-07 16:54:23 -07001526 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001527 if (mTrack == 0) return NO_INIT;
1528 return mTrack->setParameters(keyValuePairs);
1529}
1530
1531String8 MediaPlayerService::AudioOutput::getParameters(const String8& keys)
1532{
Andy Hungd1c74342015-07-07 16:54:23 -07001533 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001534 if (mTrack == 0) return String8::empty();
1535 return mTrack->getParameters(keys);
1536}
1537
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001538void MediaPlayerService::AudioOutput::setAudioAttributes(const audio_attributes_t * attributes) {
Andy Hungd1c74342015-07-07 16:54:23 -07001539 Mutex::Autolock lock(mLock);
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001540 if (attributes == NULL) {
1541 free(mAttributes);
1542 mAttributes = NULL;
1543 } else {
1544 if (mAttributes == NULL) {
1545 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1546 }
1547 memcpy(mAttributes, attributes, sizeof(audio_attributes_t));
Eric Laurent43562692015-07-15 16:49:07 -07001548 mStreamType = audio_attributes_to_stream_type(attributes);
1549 }
1550}
1551
1552void MediaPlayerService::AudioOutput::setAudioStreamType(audio_stream_type_t streamType)
1553{
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001554 Mutex::Autolock lock(mLock);
Eric Laurent43562692015-07-15 16:49:07 -07001555 // do not allow direct stream type modification if attributes have been set
1556 if (mAttributes == NULL) {
1557 mStreamType = streamType;
1558 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001559}
1560
Andy Hungd1c74342015-07-07 16:54:23 -07001561void MediaPlayerService::AudioOutput::deleteRecycledTrack_l()
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001562{
Andy Hungd1c74342015-07-07 16:54:23 -07001563 ALOGV("deleteRecycledTrack_l");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001564 if (mRecycledTrack != 0) {
1565
1566 if (mCallbackData != NULL) {
1567 mCallbackData->setOutput(NULL);
1568 mCallbackData->endTrackSwitch();
1569 }
1570
1571 if ((mRecycledTrack->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) {
1572 mRecycledTrack->flush();
1573 }
1574 // An offloaded track isn't flushed because the STREAM_END is reported
1575 // slightly prematurely to allow time for the gapless track switch
1576 // but this means that if we decide not to recycle the track there
1577 // could be a small amount of residual data still playing. We leave
1578 // AudioFlinger to drain the track.
1579
1580 mRecycledTrack.clear();
Andy Hungd1c74342015-07-07 16:54:23 -07001581 close_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001582 delete mCallbackData;
1583 mCallbackData = NULL;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001584 }
1585}
1586
Andy Hungd1c74342015-07-07 16:54:23 -07001587void MediaPlayerService::AudioOutput::close_l()
1588{
1589 mTrack.clear();
1590}
1591
Andreas Huber20111aa2009-07-14 16:56:47 -07001592status_t MediaPlayerService::AudioOutput::open(
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001593 uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
1594 audio_format_t format, int bufferCount,
Eric Laurent1948eb32012-04-13 16:50:19 -07001595 AudioCallback cb, void *cookie,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001596 audio_output_flags_t flags,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001597 const audio_offload_info_t *offloadInfo,
Andy Hung179652e2015-05-31 22:49:46 -07001598 bool doNotReconnect,
1599 uint32_t suggestedFrameCount)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001600{
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001601 ALOGV("open(%u, %d, 0x%x, 0x%x, %d, %d 0x%x)", sampleRate, channelCount, channelMask,
1602 format, bufferCount, mSessionId, flags);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001603
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001604 // offloading is only supported in callback mode for now.
1605 // offloadInfo must be present if offload flag is set
1606 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) &&
1607 ((cb == NULL) || (offloadInfo == NULL))) {
1608 return BAD_VALUE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001609 }
1610
Andy Hung179652e2015-05-31 22:49:46 -07001611 // compute frame count for the AudioTrack internal buffer
1612 size_t frameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001613 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1614 frameCount = 0; // AudioTrack will get frame count from AudioFlinger
1615 } else {
Andy Hung179652e2015-05-31 22:49:46 -07001616 // try to estimate the buffer processing fetch size from AudioFlinger.
1617 // framesPerBuffer is approximate and generally correct, except when it's not :-).
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001618 uint32_t afSampleRate;
1619 size_t afFrameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001620 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1621 return NO_INIT;
1622 }
1623 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1624 return NO_INIT;
1625 }
Andy Hung179652e2015-05-31 22:49:46 -07001626 const size_t framesPerBuffer =
1627 (unsigned long long)sampleRate * afFrameCount / afSampleRate;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001628
Andy Hung179652e2015-05-31 22:49:46 -07001629 if (bufferCount == 0) {
1630 // use suggestedFrameCount
1631 bufferCount = (suggestedFrameCount + framesPerBuffer - 1) / framesPerBuffer;
1632 }
1633 // Check argument bufferCount against the mininum buffer count
1634 if (bufferCount != 0 && bufferCount < mMinBufferCount) {
1635 ALOGV("bufferCount (%d) increased to %d", bufferCount, mMinBufferCount);
1636 bufferCount = mMinBufferCount;
1637 }
1638 // if frameCount is 0, then AudioTrack will get frame count from AudioFlinger
1639 // which will be the minimum size permitted.
1640 frameCount = bufferCount * framesPerBuffer;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001641 }
Andreas Huber20111aa2009-07-14 16:56:47 -07001642
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001643 if (channelMask == CHANNEL_MASK_USE_CHANNEL_ORDER) {
Glenn Kastenab334fd2012-03-14 12:56:06 -07001644 channelMask = audio_channel_out_mask_from_count(channelCount);
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001645 if (0 == channelMask) {
1646 ALOGE("open() error, can\'t derive mask for %d audio channels", channelCount);
1647 return NO_INIT;
1648 }
1649 }
Eric Laurent1948eb32012-04-13 16:50:19 -07001650
Andy Hungd1c74342015-07-07 16:54:23 -07001651 Mutex::Autolock lock(mLock);
Andy Hung179652e2015-05-31 22:49:46 -07001652 mCallback = cb;
1653 mCallbackCookie = cookie;
1654
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001655 // Check whether we can recycle the track
1656 bool reuse = false;
1657 bool bothOffloaded = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001658
Glenn Kasten2799d742013-05-30 14:33:29 -07001659 if (mRecycledTrack != 0) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001660 // check whether we are switching between two offloaded tracks
1661 bothOffloaded = (flags & mRecycledTrack->getFlags()
1662 & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0;
Marco Nelissen67295b52012-06-11 14:52:53 -07001663
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001664 // check if the existing track can be reused as-is, or if a new track needs to be created.
1665 reuse = true;
1666
Marco Nelissen67295b52012-06-11 14:52:53 -07001667 if ((mCallbackData == NULL && mCallback != NULL) ||
1668 (mCallbackData != NULL && mCallback == NULL)) {
1669 // recycled track uses callbacks but the caller wants to use writes, or vice versa
1670 ALOGV("can't chain callback and write");
1671 reuse = false;
1672 } else if ((mRecycledTrack->getSampleRate() != sampleRate) ||
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001673 (mRecycledTrack->channelCount() != (uint32_t)channelCount) ) {
1674 ALOGV("samplerate, channelcount differ: %u/%u Hz, %u/%d ch",
Marco Nelissen67295b52012-06-11 14:52:53 -07001675 mRecycledTrack->getSampleRate(), sampleRate,
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001676 mRecycledTrack->channelCount(), channelCount);
Marco Nelissen67295b52012-06-11 14:52:53 -07001677 reuse = false;
1678 } else if (flags != mFlags) {
1679 ALOGV("output flags differ %08x/%08x", flags, mFlags);
1680 reuse = false;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001681 } else if (mRecycledTrack->format() != format) {
1682 reuse = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001683 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001684 } else {
1685 ALOGV("no track available to recycle");
1686 }
1687
1688 ALOGV_IF(bothOffloaded, "both tracks offloaded");
1689
1690 // If we can't recycle and both tracks are offloaded
1691 // we must close the previous output before opening a new one
1692 if (bothOffloaded && !reuse) {
1693 ALOGV("both offloaded and not recycling");
Andy Hungd1c74342015-07-07 16:54:23 -07001694 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001695 }
1696
1697 sp<AudioTrack> t;
1698 CallbackData *newcbd = NULL;
1699
1700 // We don't attempt to create a new track if we are recycling an
1701 // offloaded track. But, if we are recycling a non-offloaded or we
1702 // are switching where one is offloaded and one isn't then we create
1703 // the new track in advance so that we can read additional stream info
1704
1705 if (!(reuse && bothOffloaded)) {
1706 ALOGV("creating new AudioTrack");
1707
1708 if (mCallback != NULL) {
1709 newcbd = new CallbackData(this);
1710 t = new AudioTrack(
1711 mStreamType,
1712 sampleRate,
1713 format,
1714 channelMask,
1715 frameCount,
1716 flags,
1717 CallbackWrapper,
1718 newcbd,
1719 0, // notification frames
1720 mSessionId,
1721 AudioTrack::TRANSFER_CALLBACK,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001722 offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -08001723 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001724 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001725 mAttributes,
1726 doNotReconnect);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001727 } else {
1728 t = new AudioTrack(
1729 mStreamType,
1730 sampleRate,
1731 format,
1732 channelMask,
1733 frameCount,
1734 flags,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001735 NULL, // callback
1736 NULL, // user data
1737 0, // notification frames
1738 mSessionId,
1739 AudioTrack::TRANSFER_DEFAULT,
1740 NULL, // offload info
Marco Nelissend457c972014-02-11 08:47:07 -08001741 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001742 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001743 mAttributes,
1744 doNotReconnect);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001745 }
1746
1747 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1748 ALOGE("Unable to create audio track");
1749 delete newcbd;
Glenn Kasten3e98ecd2015-05-18 13:13:24 -07001750 // t goes out of scope, so reference count drops to zero
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001751 return NO_INIT;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001752 } else {
1753 // successful AudioTrack initialization implies a legacy stream type was generated
1754 // from the audio attributes
1755 mStreamType = t->streamType();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001756 }
1757 }
1758
1759 if (reuse) {
1760 CHECK(mRecycledTrack != NULL);
1761
1762 if (!bothOffloaded) {
1763 if (mRecycledTrack->frameCount() != t->frameCount()) {
1764 ALOGV("framecount differs: %u/%u frames",
1765 mRecycledTrack->frameCount(), t->frameCount());
1766 reuse = false;
1767 }
1768 }
1769
Marco Nelissen67295b52012-06-11 14:52:53 -07001770 if (reuse) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001771 ALOGV("chaining to next output and recycling track");
Andy Hungd1c74342015-07-07 16:54:23 -07001772 close_l();
Marco Nelissen67295b52012-06-11 14:52:53 -07001773 mTrack = mRecycledTrack;
Glenn Kasten2799d742013-05-30 14:33:29 -07001774 mRecycledTrack.clear();
Marco Nelissen67295b52012-06-11 14:52:53 -07001775 if (mCallbackData != NULL) {
1776 mCallbackData->setOutput(this);
1777 }
Marco Nelissen67295b52012-06-11 14:52:53 -07001778 delete newcbd;
1779 return OK;
1780 }
Marco Nelissen67295b52012-06-11 14:52:53 -07001781 }
1782
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001783 // we're not going to reuse the track, unblock and flush it
1784 // this was done earlier if both tracks are offloaded
1785 if (!bothOffloaded) {
Andy Hungd1c74342015-07-07 16:54:23 -07001786 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001787 }
1788
1789 CHECK((t != NULL) && ((mCallback == NULL) || (newcbd != NULL)));
1790
Marco Nelissen67295b52012-06-11 14:52:53 -07001791 mCallbackData = newcbd;
Steve Block3856b092011-10-20 11:56:00 +01001792 ALOGV("setVolume");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001793 t->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07001794
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001795 mSampleRateHz = sampleRate;
Preetam Singh Ranawat2e17eef2015-08-12 12:11:46 -07001796 mFlags = flags;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001797 mMsecsPerFrame = 1E3f / (mPlaybackRate.mSpeed * sampleRate);
Andy Hungd1c74342015-07-07 16:54:23 -07001798 mFrameSize = t->frameSize();
Marco Nelissen99448602012-04-02 12:16:49 -07001799 uint32_t pos;
1800 if (t->getPosition(&pos) == OK) {
Andy Hungd1c74342015-07-07 16:54:23 -07001801 mBytesWritten = uint64_t(pos) * mFrameSize;
Marco Nelissen99448602012-04-02 12:16:49 -07001802 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001803 mTrack = t;
Eric Laurent2beeb502010-07-16 07:43:46 -07001804
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001805 status_t res = NO_ERROR;
Wei Jia0162d002015-06-09 11:59:33 -07001806 // Note some output devices may give us a direct track even though we don't specify it.
1807 // Example: Line application b/17459982.
Preetam Singh Ranawat2e17eef2015-08-12 12:11:46 -07001808 if ((t->getFlags() & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) {
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001809 res = t->setPlaybackRate(mPlaybackRate);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001810 if (res == NO_ERROR) {
1811 t->setAuxEffectSendLevel(mSendLevel);
1812 res = t->attachAuxEffect(mAuxEffectId);
1813 }
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001814 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001815 ALOGV("open() DONE status %d", res);
1816 return res;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001817}
1818
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001819status_t MediaPlayerService::AudioOutput::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001820{
Steve Block3856b092011-10-20 11:56:00 +01001821 ALOGV("start");
Andy Hungd1c74342015-07-07 16:54:23 -07001822 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001823 if (mCallbackData != NULL) {
1824 mCallbackData->endTrackSwitch();
1825 }
Glenn Kasten2799d742013-05-30 14:33:29 -07001826 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001827 mTrack->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07001828 mTrack->setAuxEffectSendLevel(mSendLevel);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001829 return mTrack->start();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001830 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001831 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001832}
1833
Marco Nelissen6b74d672012-02-28 16:07:44 -08001834void MediaPlayerService::AudioOutput::setNextOutput(const sp<AudioOutput>& nextOutput) {
Andy Hungd1c74342015-07-07 16:54:23 -07001835 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001836 mNextOutput = nextOutput;
1837}
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08001838
Marco Nelissen6b74d672012-02-28 16:07:44 -08001839void MediaPlayerService::AudioOutput::switchToNextOutput() {
1840 ALOGV("switchToNextOutput");
Andy Hungd1c74342015-07-07 16:54:23 -07001841
1842 // Try to acquire the callback lock before moving track (without incurring deadlock).
1843 const unsigned kMaxSwitchTries = 100;
1844 Mutex::Autolock lock(mLock);
1845 for (unsigned tries = 0;;) {
1846 if (mTrack == 0) {
1847 return;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001848 }
Andy Hungd1c74342015-07-07 16:54:23 -07001849 if (mNextOutput != NULL && mNextOutput != this) {
1850 if (mCallbackData != NULL) {
1851 // two alternative approaches
1852#if 1
1853 CallbackData *callbackData = mCallbackData;
1854 mLock.unlock();
1855 // proper acquisition sequence
1856 callbackData->lock();
1857 mLock.lock();
1858 // Caution: it is unlikely that someone deleted our callback or changed our target
1859 if (callbackData != mCallbackData || mNextOutput == NULL || mNextOutput == this) {
1860 // fatal if we are starved out.
1861 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
1862 "switchToNextOutput() cannot obtain correct lock sequence");
1863 callbackData->unlock();
1864 continue;
1865 }
1866 callbackData->mSwitching = true; // begin track switch
1867#else
1868 // tryBeginTrackSwitch() returns false if the callback has the lock.
1869 if (!mCallbackData->tryBeginTrackSwitch()) {
1870 // fatal if we are starved out.
1871 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
1872 "switchToNextOutput() cannot obtain callback lock");
1873 mLock.unlock();
1874 usleep(5 * 1000 /* usec */); // allow callback to use AudioOutput
1875 mLock.lock();
1876 continue;
1877 }
1878#endif
1879 }
1880
1881 Mutex::Autolock nextLock(mNextOutput->mLock);
1882
1883 // If the next output track is not NULL, then it has been
1884 // opened already for playback.
1885 // This is possible even without the next player being started,
1886 // for example, the next player could be prepared and seeked.
1887 //
1888 // Presuming it isn't advisable to force the track over.
1889 if (mNextOutput->mTrack == NULL) {
1890 ALOGD("Recycling track for gapless playback");
1891 delete mNextOutput->mCallbackData;
1892 mNextOutput->mCallbackData = mCallbackData;
1893 mNextOutput->mRecycledTrack = mTrack;
1894 mNextOutput->mSampleRateHz = mSampleRateHz;
1895 mNextOutput->mMsecsPerFrame = mMsecsPerFrame;
1896 mNextOutput->mBytesWritten = mBytesWritten;
1897 mNextOutput->mFlags = mFlags;
1898 mNextOutput->mFrameSize = mFrameSize;
1899 close_l();
1900 mCallbackData = NULL; // destruction handled by mNextOutput
1901 } else {
1902 ALOGW("Ignoring gapless playback because next player has already started");
1903 // remove track in case resource needed for future players.
1904 if (mCallbackData != NULL) {
1905 mCallbackData->endTrackSwitch(); // release lock for callbacks before close.
1906 }
1907 close_l();
1908 }
1909 }
1910 break;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001911 }
1912}
1913
Wei Jia7d3f4df2015-03-03 15:28:00 -08001914ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001915{
Andy Hungd1c74342015-07-07 16:54:23 -07001916 Mutex::Autolock lock(mLock);
Glenn Kastenadad3d72014-02-21 14:51:43 -08001917 LOG_ALWAYS_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
Andreas Huber20111aa2009-07-14 16:56:47 -07001918
Steve Block3856b092011-10-20 11:56:00 +01001919 //ALOGV("write(%p, %u)", buffer, size);
Glenn Kasten2799d742013-05-30 14:33:29 -07001920 if (mTrack != 0) {
Wei Jia7d3f4df2015-03-03 15:28:00 -08001921 ssize_t ret = mTrack->write(buffer, size, blocking);
Andy Hunga31335a2014-08-20 17:37:59 -07001922 if (ret >= 0) {
1923 mBytesWritten += ret;
1924 }
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001925 return ret;
1926 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001927 return NO_INIT;
1928}
1929
1930void MediaPlayerService::AudioOutput::stop()
1931{
Steve Block3856b092011-10-20 11:56:00 +01001932 ALOGV("stop");
Andy Hungd1c74342015-07-07 16:54:23 -07001933 Mutex::Autolock lock(mLock);
Andy Hungda17c042015-06-01 15:53:14 -07001934 mBytesWritten = 0;
Glenn Kasten2799d742013-05-30 14:33:29 -07001935 if (mTrack != 0) mTrack->stop();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001936}
1937
1938void MediaPlayerService::AudioOutput::flush()
1939{
Steve Block3856b092011-10-20 11:56:00 +01001940 ALOGV("flush");
Andy Hungd1c74342015-07-07 16:54:23 -07001941 Mutex::Autolock lock(mLock);
Andy Hungda17c042015-06-01 15:53:14 -07001942 mBytesWritten = 0;
Glenn Kasten2799d742013-05-30 14:33:29 -07001943 if (mTrack != 0) mTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001944}
1945
1946void MediaPlayerService::AudioOutput::pause()
1947{
Steve Block3856b092011-10-20 11:56:00 +01001948 ALOGV("pause");
Andy Hungd1c74342015-07-07 16:54:23 -07001949 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07001950 if (mTrack != 0) mTrack->pause();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001951}
1952
1953void MediaPlayerService::AudioOutput::close()
1954{
Steve Block3856b092011-10-20 11:56:00 +01001955 ALOGV("close");
Erik Wolsheimer7845a1f2015-10-30 12:07:52 -07001956 sp<AudioTrack> track;
1957 {
1958 Mutex::Autolock lock(mLock);
1959 track = mTrack;
1960 close_l(); // clears mTrack
1961 }
1962 // destruction of the track occurs outside of mutex.
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001963}
1964
1965void MediaPlayerService::AudioOutput::setVolume(float left, float right)
1966{
Steve Block3856b092011-10-20 11:56:00 +01001967 ALOGV("setVolume(%f, %f)", left, right);
Andy Hungd1c74342015-07-07 16:54:23 -07001968 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001969 mLeftVolume = left;
1970 mRightVolume = right;
Glenn Kasten2799d742013-05-30 14:33:29 -07001971 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001972 mTrack->setVolume(left, right);
1973 }
1974}
1975
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001976status_t MediaPlayerService::AudioOutput::setPlaybackRate(const AudioPlaybackRate &rate)
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001977{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001978 ALOGV("setPlaybackRate(%f %f %d %d)",
1979 rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Andy Hungd1c74342015-07-07 16:54:23 -07001980 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001981 if (mTrack == 0) {
1982 // remember rate so that we can set it when the track is opened
1983 mPlaybackRate = rate;
1984 return OK;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001985 }
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001986 status_t res = mTrack->setPlaybackRate(rate);
1987 if (res != NO_ERROR) {
1988 return res;
1989 }
1990 // rate.mSpeed is always greater than 0 if setPlaybackRate succeeded
1991 CHECK_GT(rate.mSpeed, 0.f);
1992 mPlaybackRate = rate;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001993 if (mSampleRateHz != 0) {
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001994 mMsecsPerFrame = 1E3f / (rate.mSpeed * mSampleRateHz);
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001995 }
1996 return res;
1997}
1998
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001999status_t MediaPlayerService::AudioOutput::getPlaybackRate(AudioPlaybackRate *rate)
2000{
2001 ALOGV("setPlaybackRate");
Andy Hungd1c74342015-07-07 16:54:23 -07002002 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07002003 if (mTrack == 0) {
2004 return NO_INIT;
2005 }
2006 *rate = mTrack->getPlaybackRate();
2007 return NO_ERROR;
2008}
2009
Eric Laurent2beeb502010-07-16 07:43:46 -07002010status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
2011{
Steve Block3856b092011-10-20 11:56:00 +01002012 ALOGV("setAuxEffectSendLevel(%f)", level);
Andy Hungd1c74342015-07-07 16:54:23 -07002013 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002014 mSendLevel = level;
Glenn Kasten2799d742013-05-30 14:33:29 -07002015 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002016 return mTrack->setAuxEffectSendLevel(level);
2017 }
2018 return NO_ERROR;
2019}
2020
2021status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
2022{
Steve Block3856b092011-10-20 11:56:00 +01002023 ALOGV("attachAuxEffect(%d)", effectId);
Andy Hungd1c74342015-07-07 16:54:23 -07002024 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07002025 mAuxEffectId = effectId;
Glenn Kasten2799d742013-05-30 14:33:29 -07002026 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07002027 return mTrack->attachAuxEffect(effectId);
2028 }
2029 return NO_ERROR;
2030}
2031
Andreas Huber20111aa2009-07-14 16:56:47 -07002032// static
2033void MediaPlayerService::AudioOutput::CallbackWrapper(
Glenn Kastend217a8c2011-06-01 15:20:35 -07002034 int event, void *cookie, void *info) {
Steve Block3856b092011-10-20 11:56:00 +01002035 //ALOGV("callbackwrapper");
Marco Nelissen6b74d672012-02-28 16:07:44 -08002036 CallbackData *data = (CallbackData*)cookie;
Andy Hungd1c74342015-07-07 16:54:23 -07002037 // lock to ensure we aren't caught in the middle of a track switch.
Marco Nelissen6b74d672012-02-28 16:07:44 -08002038 data->lock();
2039 AudioOutput *me = data->getOutput();
Andreas Huber20111aa2009-07-14 16:56:47 -07002040 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
Marco Nelissen6b74d672012-02-28 16:07:44 -08002041 if (me == NULL) {
2042 // no output set, likely because the track was scheduled to be reused
2043 // by another player, but the format turned out to be incompatible.
2044 data->unlock();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002045 if (buffer != NULL) {
2046 buffer->size = 0;
2047 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08002048 return;
2049 }
Andreas Huber20111aa2009-07-14 16:56:47 -07002050
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002051 switch(event) {
2052 case AudioTrack::EVENT_MORE_DATA: {
2053 size_t actualSize = (*me->mCallback)(
2054 me, buffer->raw, buffer->size, me->mCallbackCookie,
2055 CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002056
Andy Hung719b46b2015-05-31 22:18:25 -07002057 // Log when no data is returned from the callback.
2058 // (1) We may have no data (especially with network streaming sources).
2059 // (2) We may have reached the EOS and the audio track is not stopped yet.
2060 // Note that AwesomePlayer/AudioPlayer will only return zero size when it reaches the EOS.
2061 // NuPlayerRenderer will return zero when it doesn't have data (it doesn't block to fill).
2062 //
2063 // This is a benign busy-wait, with the next data request generated 10 ms or more later;
2064 // nevertheless for power reasons, we don't want to see too many of these.
Andreas Huber2e8ffaf2010-02-18 16:45:13 -08002065
Andy Hung719b46b2015-05-31 22:18:25 -07002066 ALOGV_IF(actualSize == 0 && buffer->size > 0, "callbackwrapper: empty buffer returned");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002067
Andy Hung719b46b2015-05-31 22:18:25 -07002068 me->mBytesWritten += actualSize; // benign race with reader.
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002069 buffer->size = actualSize;
2070 } break;
2071
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002072 case AudioTrack::EVENT_STREAM_END:
Andy Hung719b46b2015-05-31 22:18:25 -07002073 // currently only occurs for offloaded callbacks
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002074 ALOGV("callbackwrapper: deliver EVENT_STREAM_END");
2075 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2076 me->mCallbackCookie, CB_EVENT_STREAM_END);
2077 break;
2078
2079 case AudioTrack::EVENT_NEW_IAUDIOTRACK :
2080 ALOGV("callbackwrapper: deliver EVENT_TEAR_DOWN");
2081 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2082 me->mCallbackCookie, CB_EVENT_TEAR_DOWN);
2083 break;
2084
Glenn Kasten421743b2015-06-01 08:18:08 -07002085 case AudioTrack::EVENT_UNDERRUN:
Andy Hung719b46b2015-05-31 22:18:25 -07002086 // This occurs when there is no data available, typically
Glenn Kasten421743b2015-06-01 08:18:08 -07002087 // when there is a failure to supply data to the AudioTrack. It can also
2088 // occur in non-offloaded mode when the audio device comes out of standby.
2089 //
Andy Hung719b46b2015-05-31 22:18:25 -07002090 // If an AudioTrack underruns it outputs silence. Since this happens suddenly
2091 // it may sound like an audible pop or glitch.
2092 //
2093 // The underrun event is sent once per track underrun; the condition is reset
2094 // when more data is sent to the AudioTrack.
Glenn Kasten421743b2015-06-01 08:18:08 -07002095 ALOGI("callbackwrapper: EVENT_UNDERRUN (discarded)");
2096 break;
2097
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002098 default:
2099 ALOGE("received unknown event type: %d inside CallbackWrapper !", event);
Andreas Huber51c1e0e2011-04-04 11:43:40 -07002100 }
2101
Marco Nelissen6b74d672012-02-28 16:07:44 -08002102 data->unlock();
Andreas Huber20111aa2009-07-14 16:56:47 -07002103}
2104
Marco Nelissen4110c102012-03-29 09:31:28 -07002105int MediaPlayerService::AudioOutput::getSessionId() const
Eric Laurent8c563ed2010-10-07 18:23:03 -07002106{
Andy Hungd1c74342015-07-07 16:54:23 -07002107 Mutex::Autolock lock(mLock);
Eric Laurent8c563ed2010-10-07 18:23:03 -07002108 return mSessionId;
2109}
2110
Eric Laurent6f59db12013-07-26 17:16:50 -07002111uint32_t MediaPlayerService::AudioOutput::getSampleRate() const
2112{
Andy Hungd1c74342015-07-07 16:54:23 -07002113 Mutex::Autolock lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -07002114 if (mTrack == 0) return 0;
2115 return mTrack->getSampleRate();
2116}
2117
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002118////////////////////////////////////////////////////////////////////////////////
2119
2120struct CallbackThread : public Thread {
2121 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
2122 MediaPlayerBase::AudioSink::AudioCallback cb,
2123 void *cookie);
2124
2125protected:
2126 virtual ~CallbackThread();
2127
2128 virtual bool threadLoop();
2129
2130private:
2131 wp<MediaPlayerBase::AudioSink> mSink;
2132 MediaPlayerBase::AudioSink::AudioCallback mCallback;
2133 void *mCookie;
2134 void *mBuffer;
2135 size_t mBufferSize;
2136
2137 CallbackThread(const CallbackThread &);
2138 CallbackThread &operator=(const CallbackThread &);
2139};
2140
2141CallbackThread::CallbackThread(
2142 const wp<MediaPlayerBase::AudioSink> &sink,
2143 MediaPlayerBase::AudioSink::AudioCallback cb,
2144 void *cookie)
2145 : mSink(sink),
2146 mCallback(cb),
2147 mCookie(cookie),
2148 mBuffer(NULL),
2149 mBufferSize(0) {
2150}
2151
2152CallbackThread::~CallbackThread() {
2153 if (mBuffer) {
2154 free(mBuffer);
2155 mBuffer = NULL;
2156 }
2157}
2158
2159bool CallbackThread::threadLoop() {
2160 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
2161 if (sink == NULL) {
2162 return false;
2163 }
2164
2165 if (mBuffer == NULL) {
2166 mBufferSize = sink->bufferSize();
2167 mBuffer = malloc(mBufferSize);
2168 }
2169
2170 size_t actualSize =
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002171 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie,
2172 MediaPlayerBase::AudioSink::CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002173
2174 if (actualSize > 0) {
2175 sink->write(mBuffer, actualSize);
Andy Hunga31335a2014-08-20 17:37:59 -07002176 // Could return false on sink->write() error or short count.
2177 // Not necessarily appropriate but would work for AudioCache behavior.
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002178 }
2179
2180 return true;
2181}
2182
2183////////////////////////////////////////////////////////////////////////////////
2184
Gloria Wang7cf180c2011-02-19 18:37:57 -08002185void MediaPlayerService::addBatteryData(uint32_t params)
2186{
2187 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002188
2189 int32_t time = systemTime() / 1000000L;
2190
2191 // change audio output devices. This notification comes from AudioFlinger
2192 if ((params & kBatteryDataSpeakerOn)
2193 || (params & kBatteryDataOtherAudioDeviceOn)) {
2194
2195 int deviceOn[NUM_AUDIO_DEVICES];
2196 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2197 deviceOn[i] = 0;
2198 }
2199
2200 if ((params & kBatteryDataSpeakerOn)
2201 && (params & kBatteryDataOtherAudioDeviceOn)) {
2202 deviceOn[SPEAKER_AND_OTHER] = 1;
2203 } else if (params & kBatteryDataSpeakerOn) {
2204 deviceOn[SPEAKER] = 1;
2205 } else {
2206 deviceOn[OTHER_AUDIO_DEVICE] = 1;
2207 }
2208
2209 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2210 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
2211
2212 if (mBatteryAudio.refCount > 0) { // if playing audio
2213 if (!deviceOn[i]) {
2214 mBatteryAudio.lastTime[i] += time;
2215 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2216 mBatteryAudio.lastTime[i] = 0;
2217 } else {
2218 mBatteryAudio.lastTime[i] = 0 - time;
2219 }
2220 }
2221
2222 mBatteryAudio.deviceOn[i] = deviceOn[i];
2223 }
2224 }
2225 return;
2226 }
2227
Marco Nelissenb7848f12014-12-04 08:57:56 -08002228 // an audio stream is started
Gloria Wang9ee159b2011-02-24 14:51:45 -08002229 if (params & kBatteryDataAudioFlingerStart) {
2230 // record the start time only if currently no other audio
2231 // is being played
2232 if (mBatteryAudio.refCount == 0) {
2233 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2234 if (mBatteryAudio.deviceOn[i]) {
2235 mBatteryAudio.lastTime[i] -= time;
2236 }
2237 }
2238 }
2239
2240 mBatteryAudio.refCount ++;
2241 return;
2242
2243 } else if (params & kBatteryDataAudioFlingerStop) {
2244 if (mBatteryAudio.refCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002245 ALOGW("Battery track warning: refCount is <= 0");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002246 return;
2247 }
2248
2249 // record the stop time only if currently this is the only
2250 // audio being played
2251 if (mBatteryAudio.refCount == 1) {
2252 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2253 if (mBatteryAudio.deviceOn[i]) {
2254 mBatteryAudio.lastTime[i] += time;
2255 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2256 mBatteryAudio.lastTime[i] = 0;
2257 }
2258 }
2259 }
2260
2261 mBatteryAudio.refCount --;
2262 return;
2263 }
2264
Gloria Wang7cf180c2011-02-19 18:37:57 -08002265 int uid = IPCThreadState::self()->getCallingUid();
2266 if (uid == AID_MEDIA) {
2267 return;
2268 }
2269 int index = mBatteryData.indexOfKey(uid);
Gloria Wang7cf180c2011-02-19 18:37:57 -08002270
2271 if (index < 0) { // create a new entry for this UID
2272 BatteryUsageInfo info;
2273 info.audioTotalTime = 0;
2274 info.videoTotalTime = 0;
2275 info.audioLastTime = 0;
2276 info.videoLastTime = 0;
2277 info.refCount = 0;
2278
Gloria Wang9ee159b2011-02-24 14:51:45 -08002279 if (mBatteryData.add(uid, info) == NO_MEMORY) {
Steve Block29357bc2012-01-06 19:20:56 +00002280 ALOGE("Battery track error: no memory for new app");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002281 return;
2282 }
Gloria Wang7cf180c2011-02-19 18:37:57 -08002283 }
2284
2285 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
2286
2287 if (params & kBatteryDataCodecStarted) {
2288 if (params & kBatteryDataTrackAudio) {
2289 info.audioLastTime -= time;
2290 info.refCount ++;
2291 }
2292 if (params & kBatteryDataTrackVideo) {
2293 info.videoLastTime -= time;
2294 info.refCount ++;
2295 }
2296 } else {
2297 if (info.refCount == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002298 ALOGW("Battery track warning: refCount is already 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002299 return;
2300 } else if (info.refCount < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00002301 ALOGE("Battery track error: refCount < 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002302 mBatteryData.removeItem(uid);
2303 return;
2304 }
2305
2306 if (params & kBatteryDataTrackAudio) {
2307 info.audioLastTime += time;
2308 info.refCount --;
2309 }
2310 if (params & kBatteryDataTrackVideo) {
2311 info.videoLastTime += time;
2312 info.refCount --;
2313 }
2314
2315 // no stream is being played by this UID
2316 if (info.refCount == 0) {
2317 info.audioTotalTime += info.audioLastTime;
2318 info.audioLastTime = 0;
2319 info.videoTotalTime += info.videoLastTime;
2320 info.videoLastTime = 0;
2321 }
2322 }
2323}
2324
2325status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
2326 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002327
2328 // audio output devices usage
2329 int32_t time = systemTime() / 1000000L; //in ms
2330 int32_t totalTime;
2331
2332 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2333 totalTime = mBatteryAudio.totalTime[i];
2334
2335 if (mBatteryAudio.deviceOn[i]
2336 && (mBatteryAudio.lastTime[i] != 0)) {
2337 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
2338 totalTime += tmpTime;
2339 }
2340
2341 reply->writeInt32(totalTime);
2342 // reset the total time
2343 mBatteryAudio.totalTime[i] = 0;
2344 }
2345
2346 // codec usage
Gloria Wang7cf180c2011-02-19 18:37:57 -08002347 BatteryUsageInfo info;
2348 int size = mBatteryData.size();
2349
2350 reply->writeInt32(size);
2351 int i = 0;
2352
2353 while (i < size) {
2354 info = mBatteryData.valueAt(i);
2355
2356 reply->writeInt32(mBatteryData.keyAt(i)); //UID
2357 reply->writeInt32(info.audioTotalTime);
2358 reply->writeInt32(info.videoTotalTime);
2359
2360 info.audioTotalTime = 0;
2361 info.videoTotalTime = 0;
2362
2363 // remove the UID entry where no stream is being played
2364 if (info.refCount <= 0) {
2365 mBatteryData.removeItemsAt(i);
2366 size --;
2367 i --;
2368 }
2369 i++;
2370 }
2371 return NO_ERROR;
2372}
nikoa64c8c72009-07-20 15:07:26 -07002373} // namespace android