blob: 6ff37d5b8b6b900b5296c0505b2a046c47b73474 [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.
Ruben Brunk99e69712015-05-26 17:25:07 -0700289 BatteryNotifier& notifier(BatteryNotifier::getInstance());
290 notifier.noteResetVideo();
291 notifier.noteResetAudio();
Chong Zhang0b30fd42014-07-23 14:46:05 -0700292
John Grossman44a7e422012-06-21 17:29:24 -0700293 MediaPlayerFactory::registerBuiltinFactories();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800294}
295
296MediaPlayerService::~MediaPlayerService()
297{
Steve Block3856b092011-10-20 11:56:00 +0100298 ALOGV("MediaPlayerService destroyed");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800299}
300
Svet Ganovbe71aa22015-04-28 12:06:02 -0700301sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(const String16 &opPackageName)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800302{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800303 pid_t pid = IPCThreadState::self()->getCallingPid();
Svet Ganovbe71aa22015-04-28 12:06:02 -0700304 sp<MediaRecorderClient> recorder = new MediaRecorderClient(this, pid, opPackageName);
Gloria Wangdac6a312009-10-29 15:46:37 -0700305 wp<MediaRecorderClient> w = recorder;
306 Mutex::Autolock lock(mLock);
307 mMediaRecorderClients.add(w);
Steve Block3856b092011-10-20 11:56:00 +0100308 ALOGV("Create new media recorder client from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800309 return recorder;
310}
311
Gloria Wangdac6a312009-10-29 15:46:37 -0700312void MediaPlayerService::removeMediaRecorderClient(wp<MediaRecorderClient> client)
313{
314 Mutex::Autolock lock(mLock);
315 mMediaRecorderClients.remove(client);
Steve Block3856b092011-10-20 11:56:00 +0100316 ALOGV("Delete media recorder client");
Gloria Wangdac6a312009-10-29 15:46:37 -0700317}
318
Glenn Kastenf37971f2012-02-03 11:06:53 -0800319sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800320{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800321 pid_t pid = IPCThreadState::self()->getCallingPid();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800322 sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
Steve Block3856b092011-10-20 11:56:00 +0100323 ALOGV("Create new media retriever from pid %d", pid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800324 return retriever;
325}
326
Glenn Kastenf37971f2012-02-03 11:06:53 -0800327sp<IMediaPlayer> MediaPlayerService::create(const sp<IMediaPlayerClient>& client,
Dave Burked681bbb2011-08-30 14:39:17 +0100328 int audioSessionId)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800329{
Glenn Kastenf37971f2012-02-03 11:06:53 -0800330 pid_t pid = IPCThreadState::self()->getCallingPid();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800331 int32_t connId = android_atomic_inc(&mNextConnId);
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700332
333 sp<Client> c = new Client(
334 this, pid, connId, client, audioSessionId,
335 IPCThreadState::self()->getCallingUid());
336
Steve Block3856b092011-10-20 11:56:00 +0100337 ALOGV("Create new client(%d) from pid %d, uid %d, ", connId, pid,
Dave Burked681bbb2011-08-30 14:39:17 +0100338 IPCThreadState::self()->getCallingUid());
339
340 wp<Client> w = c;
341 {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800342 Mutex::Autolock lock(mLock);
343 mClients.add(w);
344 }
Andreas Hubere2b10282010-11-23 11:41:34 -0800345 return c;
346}
347
Lajos Molnar1381d4b2014-08-07 15:18:35 -0700348sp<IMediaCodecList> MediaPlayerService::getCodecList() const {
349 return MediaCodecList::getLocalInstance();
350}
351
Andreas Huber318ad9c2009-10-15 13:46:54 -0700352sp<IOMX> MediaPlayerService::getOMX() {
353 Mutex::Autolock autoLock(mLock);
354
355 if (mOMX.get() == NULL) {
356 mOMX = new OMX;
357 }
358
359 return mOMX;
Andreas Huber20111aa2009-07-14 16:56:47 -0700360}
361
Andreas Hubered3e3e02012-03-26 11:13:27 -0700362sp<ICrypto> MediaPlayerService::makeCrypto() {
Andreas Huber1bd139a2012-04-03 14:19:20 -0700363 return new Crypto;
Andreas Hubered3e3e02012-03-26 11:13:27 -0700364}
365
Jeff Tinkercc82dc62013-02-08 10:18:35 -0800366sp<IDrm> MediaPlayerService::makeDrm() {
367 return new Drm;
368}
369
Andreas Huber279dcd82013-01-30 10:41:25 -0800370sp<IHDCP> MediaPlayerService::makeHDCP(bool createEncryptionModule) {
371 return new HDCP(createEncryptionModule);
Andreas Huber59451f82012-09-18 10:36:32 -0700372}
373
Jeff Brown2013a542012-09-04 21:38:42 -0700374sp<IRemoteDisplay> MediaPlayerService::listenForRemoteDisplay(
Svet Ganovbe71aa22015-04-28 12:06:02 -0700375 const String16 &opPackageName,
Jeff Brown2013a542012-09-04 21:38:42 -0700376 const sp<IRemoteDisplayClient>& client, const String8& iface) {
Jeff Brownaba33d52012-09-07 17:38:58 -0700377 if (!checkPermission("android.permission.CONTROL_WIFI_DISPLAY")) {
378 return NULL;
379 }
380
Svet Ganovbe71aa22015-04-28 12:06:02 -0700381 return new RemoteDisplay(opPackageName, client, iface.string());
Jeff Brown2013a542012-09-04 21:38:42 -0700382}
383
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800384status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
385{
386 const size_t SIZE = 256;
387 char buffer[SIZE];
388 String8 result;
389
390 result.append(" AudioOutput\n");
391 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n",
392 mStreamType, mLeftVolume, mRightVolume);
393 result.append(buffer);
394 snprintf(buffer, 255, " msec per frame(%f), latency (%d)\n",
Eric Laurentdb354e52012-03-05 17:27:11 -0800395 mMsecsPerFrame, (mTrack != 0) ? mTrack->latency() : -1);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800396 result.append(buffer);
Eric Laurent2beeb502010-07-16 07:43:46 -0700397 snprintf(buffer, 255, " aux effect id(%d), send level (%f)\n",
398 mAuxEffectId, mSendLevel);
399 result.append(buffer);
400
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800401 ::write(fd, result.string(), result.size());
402 if (mTrack != 0) {
403 mTrack->dump(fd, args);
404 }
405 return NO_ERROR;
406}
407
Lajos Molnar6d339f12015-04-17 16:15:53 -0700408status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800409{
410 const size_t SIZE = 256;
411 char buffer[SIZE];
412 String8 result;
413 result.append(" Client\n");
414 snprintf(buffer, 255, " pid(%d), connId(%d), status(%d), looping(%s)\n",
415 mPid, mConnId, mStatus, mLoop?"true": "false");
416 result.append(buffer);
417 write(fd, result.string(), result.size());
Andreas Hubera0b1d4b2011-06-07 15:52:25 -0700418 if (mPlayer != NULL) {
419 mPlayer->dump(fd, args);
420 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800421 if (mAudioOutput != 0) {
422 mAudioOutput->dump(fd, args);
423 }
424 write(fd, "\n", 1);
425 return NO_ERROR;
426}
427
Marco Nelissenf09611f2015-02-13 14:12:42 -0800428/**
429 * The only arguments this understands right now are -c, -von and -voff,
430 * which are parsed by ALooperRoster::dump()
431 */
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800432status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
433{
434 const size_t SIZE = 256;
435 char buffer[SIZE];
436 String8 result;
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530437 SortedVector< sp<Client> > clients; //to serialise the mutex unlock & client destruction.
438 SortedVector< sp<MediaRecorderClient> > mediaRecorderClients;
439
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800440 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
441 snprintf(buffer, SIZE, "Permission Denial: "
442 "can't dump MediaPlayerService from pid=%d, uid=%d\n",
443 IPCThreadState::self()->getCallingPid(),
444 IPCThreadState::self()->getCallingUid());
445 result.append(buffer);
446 } else {
447 Mutex::Autolock lock(mLock);
448 for (int i = 0, n = mClients.size(); i < n; ++i) {
449 sp<Client> c = mClients[i].promote();
450 if (c != 0) c->dump(fd, args);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530451 clients.add(c);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800452 }
James Dongb9141222010-07-08 11:16:11 -0700453 if (mMediaRecorderClients.size() == 0) {
454 result.append(" No media recorder client\n\n");
455 } else {
456 for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
457 sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
James Donge579e282011-10-18 22:29:20 -0700458 if (c != 0) {
459 snprintf(buffer, 255, " MediaRecorderClient pid(%d)\n", c->mPid);
460 result.append(buffer);
461 write(fd, result.string(), result.size());
462 result = "\n";
463 c->dump(fd, args);
Ravi Kumar Alamanda330c8e32014-12-22 10:05:29 +0530464 mediaRecorderClients.add(c);
James Donge579e282011-10-18 22:29:20 -0700465 }
James Dongb9141222010-07-08 11:16:11 -0700466 }
Gloria Wangdac6a312009-10-29 15:46:37 -0700467 }
468
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800469 result.append(" Files opened and/or mapped:\n");
Marco Nelissenf09611f2015-02-13 14:12:42 -0800470 snprintf(buffer, SIZE, "/proc/%d/maps", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800471 FILE *f = fopen(buffer, "r");
472 if (f) {
473 while (!feof(f)) {
474 fgets(buffer, SIZE, f);
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700475 if (strstr(buffer, " /storage/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800476 strstr(buffer, " /system/sounds/") ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700477 strstr(buffer, " /data/") ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800478 strstr(buffer, " /system/media/")) {
479 result.append(" ");
480 result.append(buffer);
481 }
482 }
483 fclose(f);
484 } else {
485 result.append("couldn't open ");
486 result.append(buffer);
487 result.append("\n");
488 }
489
Marco Nelissenf09611f2015-02-13 14:12:42 -0800490 snprintf(buffer, SIZE, "/proc/%d/fd", getpid());
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800491 DIR *d = opendir(buffer);
492 if (d) {
493 struct dirent *ent;
494 while((ent = readdir(d)) != NULL) {
495 if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
Marco Nelissenf09611f2015-02-13 14:12:42 -0800496 snprintf(buffer, SIZE, "/proc/%d/fd/%s", getpid(), ent->d_name);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800497 struct stat s;
498 if (lstat(buffer, &s) == 0) {
499 if ((s.st_mode & S_IFMT) == S_IFLNK) {
500 char linkto[256];
501 int len = readlink(buffer, linkto, sizeof(linkto));
502 if(len > 0) {
503 if(len > 255) {
504 linkto[252] = '.';
505 linkto[253] = '.';
506 linkto[254] = '.';
507 linkto[255] = 0;
508 } else {
509 linkto[len] = 0;
510 }
Marco Nelissen73ac1ee2012-05-07 15:36:32 -0700511 if (strstr(linkto, "/storage/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800512 strstr(linkto, "/system/sounds/") == linkto ||
Dave Sparks02fa8342010-09-27 16:55:18 -0700513 strstr(linkto, "/data/") == linkto ||
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800514 strstr(linkto, "/system/media/") == linkto) {
515 result.append(" ");
516 result.append(buffer);
517 result.append(" -> ");
518 result.append(linkto);
519 result.append("\n");
520 }
521 }
522 } else {
523 result.append(" unexpected type for ");
524 result.append(buffer);
525 result.append("\n");
526 }
527 }
528 }
529 }
530 closedir(d);
531 } else {
532 result.append("couldn't open ");
533 result.append(buffer);
534 result.append("\n");
535 }
536
Marco Nelissenf09611f2015-02-13 14:12:42 -0800537 gLooperRoster.dump(fd, args);
538
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800539 bool dumpMem = false;
540 for (size_t i = 0; i < args.size(); i++) {
541 if (args[i] == String16("-m")) {
542 dumpMem = true;
543 }
544 }
545 if (dumpMem) {
James Dong8635b7b2011-03-14 17:01:38 -0700546 dumpMemoryAddresses(fd);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800547 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800548 }
549 write(fd, result.string(), result.size());
550 return NO_ERROR;
551}
552
553void MediaPlayerService::removeClient(wp<Client> client)
554{
555 Mutex::Autolock lock(mLock);
556 mClients.remove(client);
557}
558
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700559MediaPlayerService::Client::Client(
560 const sp<MediaPlayerService>& service, pid_t pid,
561 int32_t connId, const sp<IMediaPlayerClient>& client,
562 int audioSessionId, uid_t uid)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800563{
Steve Block3856b092011-10-20 11:56:00 +0100564 ALOGV("Client(%d) constructor", connId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800565 mPid = pid;
566 mConnId = connId;
567 mService = service;
568 mClient = client;
569 mLoop = false;
570 mStatus = NO_INIT;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700571 mAudioSessionId = audioSessionId;
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700572 mUID = uid;
John Grossmanc795b642012-02-22 15:38:35 -0800573 mRetransmitEndpointValid = false;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700574 mAudioAttributes = NULL;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700575
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800576#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000577 ALOGD("create Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800578 mAntagonizer = new Antagonizer(notify, this);
579#endif
580}
581
582MediaPlayerService::Client::~Client()
583{
Steve Block3856b092011-10-20 11:56:00 +0100584 ALOGV("Client(%d) destructor pid = %d", mConnId, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800585 mAudioOutput.clear();
586 wp<Client> client(this);
587 disconnect();
588 mService->removeClient(client);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700589 if (mAudioAttributes != NULL) {
590 free(mAudioAttributes);
591 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800592}
593
594void MediaPlayerService::Client::disconnect()
595{
Steve Block3856b092011-10-20 11:56:00 +0100596 ALOGV("disconnect(%d) from pid %d", mConnId, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800597 // grab local reference and clear main reference to prevent future
598 // access to object
599 sp<MediaPlayerBase> p;
600 {
601 Mutex::Autolock l(mLock);
602 p = mPlayer;
beanzdcfefde2012-11-05 09:51:43 +0800603 mClient.clear();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800604 }
Andreas Huber20111aa2009-07-14 16:56:47 -0700605
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800606 mPlayer.clear();
607
608 // clear the notification to prevent callbacks to dead client
609 // and reset the player. We assume the player will serialize
610 // access to itself if necessary.
611 if (p != 0) {
612 p->setNotifyCallback(0, 0);
613#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000614 ALOGD("kill Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800615 mAntagonizer->kill();
616#endif
617 p->reset();
618 }
619
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700620 disconnectNativeWindow();
621
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800622 IPCThreadState::self()->flushCommands();
623}
624
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800625sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
626{
627 // determine if we have the right player type
628 sp<MediaPlayerBase> p = mPlayer;
629 if ((p != NULL) && (p->playerType() != playerType)) {
Steve Block3856b092011-10-20 11:56:00 +0100630 ALOGV("delete player");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800631 p.clear();
632 }
633 if (p == NULL) {
Ronghua Wu68845c12015-07-21 09:50:48 -0700634 p = MediaPlayerFactory::createPlayer(playerType, this, notify, mPid);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800635 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700636
Jason Simmonsdb29e522011-08-12 13:46:55 -0700637 if (p != NULL) {
638 p->setUID(mUID);
639 }
Andreas Huber9b80c2b2011-06-30 15:47:02 -0700640
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800641 return p;
642}
643
John Grossmanc795b642012-02-22 15:38:35 -0800644sp<MediaPlayerBase> MediaPlayerService::Client::setDataSource_pre(
645 player_type playerType)
646{
647 ALOGV("player type = %d", playerType);
648
649 // create the right type of player
650 sp<MediaPlayerBase> p = createPlayer(playerType);
651 if (p == NULL) {
652 return p;
653 }
654
655 if (!p->hardwareOutput()) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -0700656 Mutex::Autolock l(mLock);
Marco Nelissend457c972014-02-11 08:47:07 -0800657 mAudioOutput = new AudioOutput(mAudioSessionId, IPCThreadState::self()->getCallingUid(),
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -0700658 mPid, mAudioAttributes);
John Grossmanc795b642012-02-22 15:38:35 -0800659 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
660 }
661
662 return p;
663}
664
665void MediaPlayerService::Client::setDataSource_post(
666 const sp<MediaPlayerBase>& p,
667 status_t status)
668{
669 ALOGV(" setDataSource");
670 mStatus = status;
671 if (mStatus != OK) {
672 ALOGE(" error: %d", mStatus);
673 return;
674 }
675
676 // Set the re-transmission endpoint if one was chosen.
677 if (mRetransmitEndpointValid) {
678 mStatus = p->setRetransmitEndpoint(&mRetransmitEndpoint);
679 if (mStatus != NO_ERROR) {
680 ALOGE("setRetransmitEndpoint error: %d", mStatus);
681 }
682 }
683
684 if (mStatus == OK) {
685 mPlayer = p;
686 }
687}
688
Andreas Huber2db84552010-01-28 11:19:57 -0800689status_t MediaPlayerService::Client::setDataSource(
Andreas Huber1b86fe02014-01-29 11:13:26 -0800690 const sp<IMediaHTTPService> &httpService,
691 const char *url,
692 const KeyedVector<String8, String8> *headers)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800693{
Steve Block3856b092011-10-20 11:56:00 +0100694 ALOGV("setDataSource(%s)", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800695 if (url == NULL)
696 return UNKNOWN_ERROR;
697
Dave Burked681bbb2011-08-30 14:39:17 +0100698 if ((strncmp(url, "http://", 7) == 0) ||
699 (strncmp(url, "https://", 8) == 0) ||
700 (strncmp(url, "rtsp://", 7) == 0)) {
701 if (!checkPermission("android.permission.INTERNET")) {
702 return PERMISSION_DENIED;
703 }
704 }
705
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800706 if (strncmp(url, "content://", 10) == 0) {
707 // get a filedescriptor for the content Uri and
708 // pass it to the setDataSource(fd) method
709
710 String16 url16(url);
711 int fd = android::openContentProviderFile(url16);
712 if (fd < 0)
713 {
Steve Block29357bc2012-01-06 19:20:56 +0000714 ALOGE("Couldn't open fd for %s", url);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800715 return UNKNOWN_ERROR;
716 }
717 setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
718 close(fd);
719 return mStatus;
720 } else {
John Grossman44a7e422012-06-21 17:29:24 -0700721 player_type playerType = MediaPlayerFactory::getPlayerType(this, url);
John Grossmanc795b642012-02-22 15:38:35 -0800722 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
723 if (p == NULL) {
724 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800725 }
726
Andreas Huber1b86fe02014-01-29 11:13:26 -0800727 setDataSource_post(p, p->setDataSource(httpService, url, headers));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800728 return mStatus;
729 }
730}
731
732status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
733{
Marco Nelissen83b0fd92015-09-16 13:48:07 -0700734 ALOGV("setDataSource fd=%d (%s), offset=%lld, length=%lld",
735 fd, nameForFd(fd).c_str(), (long long) offset, (long long) length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800736 struct stat sb;
737 int ret = fstat(fd, &sb);
738 if (ret != 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000739 ALOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800740 return UNKNOWN_ERROR;
741 }
742
Ying Wang5fde15d2015-04-20 22:13:22 -0700743 ALOGV("st_dev = %llu", static_cast<uint64_t>(sb.st_dev));
Steve Block3856b092011-10-20 11:56:00 +0100744 ALOGV("st_mode = %u", sb.st_mode);
Mark Salyzyn77342f72014-06-18 16:31:32 -0700745 ALOGV("st_uid = %lu", static_cast<unsigned long>(sb.st_uid));
746 ALOGV("st_gid = %lu", static_cast<unsigned long>(sb.st_gid));
Steve Block3856b092011-10-20 11:56:00 +0100747 ALOGV("st_size = %llu", sb.st_size);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800748
749 if (offset >= sb.st_size) {
Steve Block29357bc2012-01-06 19:20:56 +0000750 ALOGE("offset error");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800751 return UNKNOWN_ERROR;
752 }
753 if (offset + length > sb.st_size) {
754 length = sb.st_size - offset;
Steve Block3856b092011-10-20 11:56:00 +0100755 ALOGV("calculated length = %lld", length);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800756 }
757
John Grossman44a7e422012-06-21 17:29:24 -0700758 player_type playerType = MediaPlayerFactory::getPlayerType(this,
759 fd,
760 offset,
761 length);
John Grossmanc795b642012-02-22 15:38:35 -0800762 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
763 if (p == NULL) {
764 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800765 }
766
767 // now set data source
John Grossmanc795b642012-02-22 15:38:35 -0800768 setDataSource_post(p, p->setDataSource(fd, offset, length));
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800769 return mStatus;
770}
771
Andreas Hubere2b10282010-11-23 11:41:34 -0800772status_t MediaPlayerService::Client::setDataSource(
773 const sp<IStreamSource> &source) {
774 // create the right type of player
John Grossman44a7e422012-06-21 17:29:24 -0700775 player_type playerType = MediaPlayerFactory::getPlayerType(this, source);
John Grossmanc795b642012-02-22 15:38:35 -0800776 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
Andreas Hubere2b10282010-11-23 11:41:34 -0800777 if (p == NULL) {
778 return NO_INIT;
779 }
780
Andreas Hubere2b10282010-11-23 11:41:34 -0800781 // now set data source
John Grossmanc795b642012-02-22 15:38:35 -0800782 setDataSource_post(p, p->setDataSource(source));
Andreas Hubere2b10282010-11-23 11:41:34 -0800783 return mStatus;
784}
785
Chris Watkins99f31602015-03-20 13:06:33 -0700786status_t MediaPlayerService::Client::setDataSource(
787 const sp<IDataSource> &source) {
788 sp<DataSource> dataSource = DataSource::CreateFromIDataSource(source);
789 player_type playerType = MediaPlayerFactory::getPlayerType(this, dataSource);
790 sp<MediaPlayerBase> p = setDataSource_pre(playerType);
791 if (p == NULL) {
792 return NO_INIT;
793 }
794 // now set data source
795 setDataSource_post(p, p->setDataSource(dataSource));
796 return mStatus;
797}
798
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700799void MediaPlayerService::Client::disconnectNativeWindow() {
800 if (mConnectedWindow != NULL) {
801 status_t err = native_window_api_disconnect(mConnectedWindow.get(),
802 NATIVE_WINDOW_API_MEDIA);
803
804 if (err != OK) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000805 ALOGW("native_window_api_disconnect returned an error: %s (%d)",
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700806 strerror(-err), err);
807 }
808 }
809 mConnectedWindow.clear();
810}
811
Glenn Kasten11731182011-02-08 17:26:17 -0800812status_t MediaPlayerService::Client::setVideoSurfaceTexture(
Andy McFadden484566c2012-12-18 09:46:54 -0800813 const sp<IGraphicBufferProducer>& bufferProducer)
Glenn Kasten11731182011-02-08 17:26:17 -0800814{
Andy McFadden484566c2012-12-18 09:46:54 -0800815 ALOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, bufferProducer.get());
Glenn Kasten11731182011-02-08 17:26:17 -0800816 sp<MediaPlayerBase> p = getPlayer();
817 if (p == 0) return UNKNOWN_ERROR;
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700818
Marco Nelissenf8880202014-11-14 07:58:25 -0800819 sp<IBinder> binder(IInterface::asBinder(bufferProducer));
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700820 if (mConnectedWindowBinder == binder) {
821 return OK;
822 }
823
824 sp<ANativeWindow> anw;
Andy McFadden484566c2012-12-18 09:46:54 -0800825 if (bufferProducer != NULL) {
Marco Nelissenee08f7e2013-09-16 13:30:01 -0700826 anw = new Surface(bufferProducer, true /* controlledByApp */);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700827 status_t err = native_window_api_connect(anw.get(),
828 NATIVE_WINDOW_API_MEDIA);
829
830 if (err != OK) {
Steve Block29357bc2012-01-06 19:20:56 +0000831 ALOGE("setVideoSurfaceTexture failed: %d", err);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700832 // Note that we must do the reset before disconnecting from the ANW.
833 // Otherwise queue/dequeue calls could be made on the disconnected
834 // ANW, which may result in errors.
835 reset();
836
837 disconnectNativeWindow();
838
839 return err;
840 }
841 }
842
Andy McFadden484566c2012-12-18 09:46:54 -0800843 // Note that we must set the player's new GraphicBufferProducer before
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700844 // disconnecting the old one. Otherwise queue/dequeue calls could be made
845 // on the disconnected ANW, which may result in errors.
Andy McFadden484566c2012-12-18 09:46:54 -0800846 status_t err = p->setVideoSurfaceTexture(bufferProducer);
Jamie Gennis7dae00b2011-10-26 18:36:31 -0700847
848 disconnectNativeWindow();
849
850 mConnectedWindow = anw;
851
852 if (err == OK) {
853 mConnectedWindowBinder = binder;
854 } else {
855 disconnectNativeWindow();
856 }
857
858 return err;
Glenn Kasten11731182011-02-08 17:26:17 -0800859}
860
Nicolas Catania1d187f12009-05-12 23:25:55 -0700861status_t MediaPlayerService::Client::invoke(const Parcel& request,
862 Parcel *reply)
863{
864 sp<MediaPlayerBase> p = getPlayer();
865 if (p == NULL) return UNKNOWN_ERROR;
866 return p->invoke(request, reply);
867}
868
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700869// This call doesn't need to access the native player.
870status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
871{
872 status_t status;
nikoa64c8c72009-07-20 15:07:26 -0700873 media::Metadata::Filter allow, drop;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700874
Nicolas Catania48290382009-07-10 13:53:06 -0700875 if (unmarshallFilter(filter, &allow, &status) &&
876 unmarshallFilter(filter, &drop, &status)) {
877 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700878
879 mMetadataAllow = allow;
880 mMetadataDrop = drop;
881 }
882 return status;
883}
884
Nicolas Catania48290382009-07-10 13:53:06 -0700885status_t MediaPlayerService::Client::getMetadata(
Mark Salyzyn77342f72014-06-18 16:31:32 -0700886 bool update_only, bool /*apply_filter*/, Parcel *reply)
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700887{
nikoa64c8c72009-07-20 15:07:26 -0700888 sp<MediaPlayerBase> player = getPlayer();
889 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania48290382009-07-10 13:53:06 -0700890
nikod608a812009-07-16 16:39:53 -0700891 status_t status;
892 // Placeholder for the return code, updated by the caller.
893 reply->writeInt32(-1);
894
nikoa64c8c72009-07-20 15:07:26 -0700895 media::Metadata::Filter ids;
Nicolas Catania48290382009-07-10 13:53:06 -0700896
897 // We don't block notifications while we fetch the data. We clear
898 // mMetadataUpdated first so we don't lose notifications happening
899 // during the rest of this call.
900 {
901 Mutex::Autolock lock(mLock);
902 if (update_only) {
nikod608a812009-07-16 16:39:53 -0700903 ids = mMetadataUpdated;
Nicolas Catania48290382009-07-10 13:53:06 -0700904 }
905 mMetadataUpdated.clear();
906 }
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700907
nikoa64c8c72009-07-20 15:07:26 -0700908 media::Metadata metadata(reply);
Nicolas Catania48290382009-07-10 13:53:06 -0700909
nikoa64c8c72009-07-20 15:07:26 -0700910 metadata.appendHeader();
911 status = player->getMetadata(ids, reply);
nikod608a812009-07-16 16:39:53 -0700912
913 if (status != OK) {
nikoa64c8c72009-07-20 15:07:26 -0700914 metadata.resetParcel();
Steve Block29357bc2012-01-06 19:20:56 +0000915 ALOGE("getMetadata failed %d", status);
nikod608a812009-07-16 16:39:53 -0700916 return status;
917 }
918
919 // FIXME: Implement filtering on the result. Not critical since
920 // filtering takes place on the update notifications already. This
921 // would be when all the metadata are fetch and a filter is set.
922
nikod608a812009-07-16 16:39:53 -0700923 // Everything is fine, update the metadata length.
nikoa64c8c72009-07-20 15:07:26 -0700924 metadata.updateLength();
nikod608a812009-07-16 16:39:53 -0700925 return OK;
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700926}
927
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800928status_t MediaPlayerService::Client::prepareAsync()
929{
Steve Block3856b092011-10-20 11:56:00 +0100930 ALOGV("[%d] prepareAsync", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800931 sp<MediaPlayerBase> p = getPlayer();
932 if (p == 0) return UNKNOWN_ERROR;
933 status_t ret = p->prepareAsync();
934#if CALLBACK_ANTAGONIZER
Steve Blockb8a80522011-12-20 16:23:08 +0000935 ALOGD("start Antagonizer");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800936 if (ret == NO_ERROR) mAntagonizer->start();
937#endif
938 return ret;
939}
940
941status_t MediaPlayerService::Client::start()
942{
Steve Block3856b092011-10-20 11:56:00 +0100943 ALOGV("[%d] start", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800944 sp<MediaPlayerBase> p = getPlayer();
945 if (p == 0) return UNKNOWN_ERROR;
946 p->setLooping(mLoop);
947 return p->start();
948}
949
950status_t MediaPlayerService::Client::stop()
951{
Steve Block3856b092011-10-20 11:56:00 +0100952 ALOGV("[%d] stop", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800953 sp<MediaPlayerBase> p = getPlayer();
954 if (p == 0) return UNKNOWN_ERROR;
955 return p->stop();
956}
957
958status_t MediaPlayerService::Client::pause()
959{
Steve Block3856b092011-10-20 11:56:00 +0100960 ALOGV("[%d] pause", mConnId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800961 sp<MediaPlayerBase> p = getPlayer();
962 if (p == 0) return UNKNOWN_ERROR;
963 return p->pause();
964}
965
966status_t MediaPlayerService::Client::isPlaying(bool* state)
967{
968 *state = false;
969 sp<MediaPlayerBase> p = getPlayer();
970 if (p == 0) return UNKNOWN_ERROR;
971 *state = p->isPlaying();
Steve Block3856b092011-10-20 11:56:00 +0100972 ALOGV("[%d] isPlaying: %d", mConnId, *state);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800973 return NO_ERROR;
974}
975
Lajos Molnar3a474aa2015-04-24 17:10:07 -0700976status_t MediaPlayerService::Client::setPlaybackSettings(const AudioPlaybackRate& rate)
Wei Jia98160162015-02-04 17:01:11 -0800977{
Lajos Molnar3a474aa2015-04-24 17:10:07 -0700978 ALOGV("[%d] setPlaybackSettings(%f, %f, %d, %d)",
979 mConnId, rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Wei Jia98160162015-02-04 17:01:11 -0800980 sp<MediaPlayerBase> p = getPlayer();
981 if (p == 0) return UNKNOWN_ERROR;
Lajos Molnar3a474aa2015-04-24 17:10:07 -0700982 return p->setPlaybackSettings(rate);
983}
984
985status_t MediaPlayerService::Client::getPlaybackSettings(AudioPlaybackRate* rate /* nonnull */)
986{
987 sp<MediaPlayerBase> p = getPlayer();
988 if (p == 0) return UNKNOWN_ERROR;
989 status_t ret = p->getPlaybackSettings(rate);
990 if (ret == NO_ERROR) {
991 ALOGV("[%d] getPlaybackSettings(%f, %f, %d, %d)",
992 mConnId, rate->mSpeed, rate->mPitch, rate->mFallbackMode, rate->mStretchMode);
993 } else {
994 ALOGV("[%d] getPlaybackSettings returned %d", mConnId, ret);
995 }
996 return ret;
997}
998
999status_t MediaPlayerService::Client::setSyncSettings(
1000 const AVSyncSettings& sync, float videoFpsHint)
1001{
1002 ALOGV("[%d] setSyncSettings(%u, %u, %f, %f)",
1003 mConnId, sync.mSource, sync.mAudioAdjustMode, sync.mTolerance, videoFpsHint);
1004 sp<MediaPlayerBase> p = getPlayer();
1005 if (p == 0) return UNKNOWN_ERROR;
1006 return p->setSyncSettings(sync, videoFpsHint);
1007}
1008
1009status_t MediaPlayerService::Client::getSyncSettings(
1010 AVSyncSettings* sync /* nonnull */, float* videoFps /* nonnull */)
1011{
1012 sp<MediaPlayerBase> p = getPlayer();
1013 if (p == 0) return UNKNOWN_ERROR;
1014 status_t ret = p->getSyncSettings(sync, videoFps);
1015 if (ret == NO_ERROR) {
1016 ALOGV("[%d] getSyncSettings(%u, %u, %f, %f)",
1017 mConnId, sync->mSource, sync->mAudioAdjustMode, sync->mTolerance, *videoFps);
1018 } else {
1019 ALOGV("[%d] getSyncSettings returned %d", mConnId, ret);
1020 }
1021 return ret;
Wei Jia98160162015-02-04 17:01:11 -08001022}
1023
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001024status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
1025{
Steve Block3856b092011-10-20 11:56:00 +01001026 ALOGV("getCurrentPosition");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001027 sp<MediaPlayerBase> p = getPlayer();
1028 if (p == 0) return UNKNOWN_ERROR;
1029 status_t ret = p->getCurrentPosition(msec);
1030 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001031 ALOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001032 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001033 ALOGE("getCurrentPosition returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001034 }
1035 return ret;
1036}
1037
1038status_t MediaPlayerService::Client::getDuration(int *msec)
1039{
Steve Block3856b092011-10-20 11:56:00 +01001040 ALOGV("getDuration");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001041 sp<MediaPlayerBase> p = getPlayer();
1042 if (p == 0) return UNKNOWN_ERROR;
1043 status_t ret = p->getDuration(msec);
1044 if (ret == NO_ERROR) {
Steve Block3856b092011-10-20 11:56:00 +01001045 ALOGV("[%d] getDuration = %d", mConnId, *msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001046 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001047 ALOGE("getDuration returned %d", ret);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001048 }
1049 return ret;
1050}
1051
Marco Nelissen6b74d672012-02-28 16:07:44 -08001052status_t MediaPlayerService::Client::setNextPlayer(const sp<IMediaPlayer>& player) {
1053 ALOGV("setNextPlayer");
1054 Mutex::Autolock l(mLock);
1055 sp<Client> c = static_cast<Client*>(player.get());
1056 mNextClient = c;
John Grossman5f7e55e2012-08-24 14:47:25 -07001057
1058 if (c != NULL) {
1059 if (mAudioOutput != NULL) {
1060 mAudioOutput->setNextOutput(c->mAudioOutput);
1061 } else if ((mPlayer != NULL) && !mPlayer->hardwareOutput()) {
1062 ALOGE("no current audio output");
1063 }
1064
1065 if ((mPlayer != NULL) && (mNextClient->getPlayer() != NULL)) {
1066 mPlayer->setNextPlayer(mNextClient->getPlayer());
1067 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001068 }
John Grossman5f7e55e2012-08-24 14:47:25 -07001069
Marco Nelissen6b74d672012-02-28 16:07:44 -08001070 return OK;
1071}
1072
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001073status_t MediaPlayerService::Client::seekTo(int msec)
1074{
Steve Block3856b092011-10-20 11:56:00 +01001075 ALOGV("[%d] seekTo(%d)", mConnId, msec);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001076 sp<MediaPlayerBase> p = getPlayer();
1077 if (p == 0) return UNKNOWN_ERROR;
1078 return p->seekTo(msec);
1079}
1080
1081status_t MediaPlayerService::Client::reset()
1082{
Steve Block3856b092011-10-20 11:56:00 +01001083 ALOGV("[%d] reset", mConnId);
John Grossmanc795b642012-02-22 15:38:35 -08001084 mRetransmitEndpointValid = false;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001085 sp<MediaPlayerBase> p = getPlayer();
1086 if (p == 0) return UNKNOWN_ERROR;
1087 return p->reset();
1088}
1089
Glenn Kastenfff6d712012-01-12 16:38:12 -08001090status_t MediaPlayerService::Client::setAudioStreamType(audio_stream_type_t type)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001091{
Steve Block3856b092011-10-20 11:56:00 +01001092 ALOGV("[%d] setAudioStreamType(%d)", mConnId, type);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001093 // TODO: for hardware output, call player instead
1094 Mutex::Autolock l(mLock);
1095 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1096 return NO_ERROR;
1097}
1098
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001099status_t MediaPlayerService::Client::setAudioAttributes_l(const Parcel &parcel)
1100{
1101 if (mAudioAttributes != NULL) { free(mAudioAttributes); }
1102 mAudioAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001103 if (mAudioAttributes == NULL) {
1104 return NO_MEMORY;
1105 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001106 unmarshallAudioAttributes(parcel, mAudioAttributes);
1107
1108 ALOGV("setAudioAttributes_l() usage=%d content=%d flags=0x%x tags=%s",
1109 mAudioAttributes->usage, mAudioAttributes->content_type, mAudioAttributes->flags,
1110 mAudioAttributes->tags);
1111
1112 if (mAudioOutput != 0) {
1113 mAudioOutput->setAudioAttributes(mAudioAttributes);
1114 }
1115 return NO_ERROR;
1116}
1117
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001118status_t MediaPlayerService::Client::setLooping(int loop)
1119{
Steve Block3856b092011-10-20 11:56:00 +01001120 ALOGV("[%d] setLooping(%d)", mConnId, loop);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001121 mLoop = loop;
1122 sp<MediaPlayerBase> p = getPlayer();
1123 if (p != 0) return p->setLooping(loop);
1124 return NO_ERROR;
1125}
1126
1127status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1128{
Steve Block3856b092011-10-20 11:56:00 +01001129 ALOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
John Grossman761defc2012-02-09 15:09:05 -08001130
1131 // for hardware output, call player instead
1132 sp<MediaPlayerBase> p = getPlayer();
1133 {
1134 Mutex::Autolock l(mLock);
1135 if (p != 0 && p->hardwareOutput()) {
1136 MediaPlayerHWInterface* hwp =
1137 reinterpret_cast<MediaPlayerHWInterface*>(p.get());
1138 return hwp->setVolume(leftVolume, rightVolume);
1139 } else {
1140 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1141 return NO_ERROR;
1142 }
1143 }
1144
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001145 return NO_ERROR;
1146}
1147
Eric Laurent2beeb502010-07-16 07:43:46 -07001148status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1149{
Steve Block3856b092011-10-20 11:56:00 +01001150 ALOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
Eric Laurent2beeb502010-07-16 07:43:46 -07001151 Mutex::Autolock l(mLock);
1152 if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1153 return NO_ERROR;
1154}
1155
1156status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1157{
Steve Block3856b092011-10-20 11:56:00 +01001158 ALOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
Eric Laurent2beeb502010-07-16 07:43:46 -07001159 Mutex::Autolock l(mLock);
1160 if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1161 return NO_ERROR;
1162}
Nicolas Catania48290382009-07-10 13:53:06 -07001163
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001164status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
Steve Block3856b092011-10-20 11:56:00 +01001165 ALOGV("[%d] setParameter(%d)", mConnId, key);
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001166 switch (key) {
1167 case KEY_PARAMETER_AUDIO_ATTRIBUTES:
1168 {
1169 Mutex::Autolock l(mLock);
1170 return setAudioAttributes_l(request);
1171 }
1172 default:
1173 sp<MediaPlayerBase> p = getPlayer();
1174 if (p == 0) { return UNKNOWN_ERROR; }
1175 return p->setParameter(key, request);
1176 }
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001177}
1178
1179status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
Steve Block3856b092011-10-20 11:56:00 +01001180 ALOGV("[%d] getParameter(%d)", mConnId, key);
Gloria Wang4f9e47f2011-04-25 17:28:22 -07001181 sp<MediaPlayerBase> p = getPlayer();
1182 if (p == 0) return UNKNOWN_ERROR;
1183 return p->getParameter(key, reply);
1184}
1185
John Grossmanc795b642012-02-22 15:38:35 -08001186status_t MediaPlayerService::Client::setRetransmitEndpoint(
1187 const struct sockaddr_in* endpoint) {
1188
1189 if (NULL != endpoint) {
1190 uint32_t a = ntohl(endpoint->sin_addr.s_addr);
1191 uint16_t p = ntohs(endpoint->sin_port);
1192 ALOGV("[%d] setRetransmitEndpoint(%u.%u.%u.%u:%hu)", mConnId,
1193 (a >> 24), (a >> 16) & 0xFF, (a >> 8) & 0xFF, (a & 0xFF), p);
1194 } else {
1195 ALOGV("[%d] setRetransmitEndpoint = <none>", mConnId);
1196 }
1197
1198 sp<MediaPlayerBase> p = getPlayer();
1199
1200 // Right now, the only valid time to set a retransmit endpoint is before
1201 // player selection has been made (since the presence or absence of a
1202 // retransmit endpoint is going to determine which player is selected during
1203 // setDataSource).
1204 if (p != 0) return INVALID_OPERATION;
1205
1206 if (NULL != endpoint) {
1207 mRetransmitEndpoint = *endpoint;
1208 mRetransmitEndpointValid = true;
1209 } else {
1210 mRetransmitEndpointValid = false;
1211 }
1212
1213 return NO_ERROR;
1214}
1215
John Grossman44a7e422012-06-21 17:29:24 -07001216status_t MediaPlayerService::Client::getRetransmitEndpoint(
1217 struct sockaddr_in* endpoint)
1218{
1219 if (NULL == endpoint)
1220 return BAD_VALUE;
1221
1222 sp<MediaPlayerBase> p = getPlayer();
1223
1224 if (p != NULL)
1225 return p->getRetransmitEndpoint(endpoint);
1226
1227 if (!mRetransmitEndpointValid)
1228 return NO_INIT;
1229
1230 *endpoint = mRetransmitEndpoint;
1231
1232 return NO_ERROR;
1233}
1234
Gloria Wangb483c472011-04-11 17:23:27 -07001235void MediaPlayerService::Client::notify(
1236 void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001237{
1238 Client* client = static_cast<Client*>(cookie);
James Dongb8a98252012-08-26 16:13:03 -07001239 if (client == NULL) {
1240 return;
1241 }
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001242
James Dongb8a98252012-08-26 16:13:03 -07001243 sp<IMediaPlayerClient> c;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001244 {
1245 Mutex::Autolock l(client->mLock);
James Dongb8a98252012-08-26 16:13:03 -07001246 c = client->mClient;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001247 if (msg == MEDIA_PLAYBACK_COMPLETE && client->mNextClient != NULL) {
John Grossmancb0b7552012-08-23 17:47:31 -07001248 if (client->mAudioOutput != NULL)
1249 client->mAudioOutput->switchToNextOutput();
Marco Nelissen6b74d672012-02-28 16:07:44 -08001250 client->mNextClient->start();
1251 client->mNextClient->mClient->notify(MEDIA_INFO, MEDIA_INFO_STARTED_AS_NEXT, 0, obj);
1252 }
1253 }
1254
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001255 if (MEDIA_INFO == msg &&
Nicolas Catania48290382009-07-10 13:53:06 -07001256 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikoa64c8c72009-07-20 15:07:26 -07001257 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania48290382009-07-10 13:53:06 -07001258
1259 if(client->shouldDropMetadata(metadata_type)) {
1260 return;
1261 }
1262
1263 // Update the list of metadata that have changed. getMetadata
1264 // also access mMetadataUpdated and clears it.
1265 client->addNewMetadataUpdate(metadata_type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001266 }
James Dongb8a98252012-08-26 16:13:03 -07001267
1268 if (c != NULL) {
1269 ALOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
1270 c->notify(msg, ext1, ext2, obj);
1271 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001272}
1273
Nicolas Catania48290382009-07-10 13:53:06 -07001274
nikoa64c8c72009-07-20 15:07:26 -07001275bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001276{
Nicolas Catania48290382009-07-10 13:53:06 -07001277 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001278
Nicolas Catania48290382009-07-10 13:53:06 -07001279 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001280 return true;
1281 }
1282
Nicolas Catania48290382009-07-10 13:53:06 -07001283 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001284 return false;
Nicolas Catania48290382009-07-10 13:53:06 -07001285 } else {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001286 return true;
1287 }
1288}
1289
Nicolas Catania48290382009-07-10 13:53:06 -07001290
nikoa64c8c72009-07-20 15:07:26 -07001291void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania48290382009-07-10 13:53:06 -07001292 Mutex::Autolock lock(mLock);
1293 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1294 mMetadataUpdated.add(metadata_type);
1295 }
1296}
1297
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001298#if CALLBACK_ANTAGONIZER
1299const int Antagonizer::interval = 10000; // 10 msecs
1300
1301Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1302 mExit(false), mActive(false), mClient(client), mCb(cb)
1303{
1304 createThread(callbackThread, this);
1305}
1306
1307void Antagonizer::kill()
1308{
1309 Mutex::Autolock _l(mLock);
1310 mActive = false;
1311 mExit = true;
1312 mCondition.wait(mLock);
1313}
1314
1315int Antagonizer::callbackThread(void* user)
1316{
Steve Blockb8a80522011-12-20 16:23:08 +00001317 ALOGD("Antagonizer started");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001318 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1319 while (!p->mExit) {
1320 if (p->mActive) {
Steve Block3856b092011-10-20 11:56:00 +01001321 ALOGV("send event");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001322 p->mCb(p->mClient, 0, 0, 0);
1323 }
1324 usleep(interval);
1325 }
1326 Mutex::Autolock _l(p->mLock);
1327 p->mCondition.signal();
Steve Blockb8a80522011-12-20 16:23:08 +00001328 ALOGD("Antagonizer stopped");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001329 return 0;
1330}
1331#endif
1332
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001333#undef LOG_TAG
1334#define LOG_TAG "AudioSink"
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001335MediaPlayerService::AudioOutput::AudioOutput(int sessionId, int uid, int pid,
1336 const audio_attributes_t* attr)
Andreas Huber20111aa2009-07-14 16:56:47 -07001337 : mCallback(NULL),
Eric Laurenta514bdb2010-06-21 09:27:30 -07001338 mCallbackCookie(NULL),
Marco Nelissen6b74d672012-02-28 16:07:44 -08001339 mCallbackData(NULL),
Marco Nelissen4110c102012-03-29 09:31:28 -07001340 mBytesWritten(0),
Andy Hungd1c74342015-07-07 16:54:23 -07001341 mStreamType(AUDIO_STREAM_MUSIC),
Andy Hungd1c74342015-07-07 16:54:23 -07001342 mLeftVolume(1.0),
1343 mRightVolume(1.0),
1344 mPlaybackRate(AUDIO_PLAYBACK_RATE_DEFAULT),
1345 mSampleRateHz(0),
1346 mMsecsPerFrame(0),
1347 mFrameSize(0),
Eric Laurent1948eb32012-04-13 16:50:19 -07001348 mSessionId(sessionId),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001349 mUid(uid),
Marco Nelissend457c972014-02-11 08:47:07 -08001350 mPid(pid),
Andy Hungd1c74342015-07-07 16:54:23 -07001351 mSendLevel(0.0),
1352 mAuxEffectId(0),
1353 mFlags(AUDIO_OUTPUT_FLAG_NONE)
1354{
Steve Block3856b092011-10-20 11:56:00 +01001355 ALOGV("AudioOutput(%d)", sessionId);
Eric Laurent43562692015-07-15 16:49:07 -07001356 if (attr != NULL) {
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001357 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1358 if (mAttributes != NULL) {
1359 memcpy(mAttributes, attr, sizeof(audio_attributes_t));
1360 mStreamType = audio_attributes_to_stream_type(attr);
1361 }
1362 } else {
1363 mAttributes = NULL;
Eric Laurent43562692015-07-15 16:49:07 -07001364 }
1365
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001366 setMinBufferCount();
1367}
1368
1369MediaPlayerService::AudioOutput::~AudioOutput()
1370{
1371 close();
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001372 free(mAttributes);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001373 delete mCallbackData;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001374}
1375
Andy Hungd1c74342015-07-07 16:54:23 -07001376//static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001377void MediaPlayerService::AudioOutput::setMinBufferCount()
1378{
1379 char value[PROPERTY_VALUE_MAX];
1380 if (property_get("ro.kernel.qemu", value, 0)) {
1381 mIsOnEmulator = true;
1382 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1383 }
1384}
1385
Andy Hungd1c74342015-07-07 16:54:23 -07001386// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001387bool MediaPlayerService::AudioOutput::isOnEmulator()
1388{
Andy Hungd1c74342015-07-07 16:54:23 -07001389 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001390 return mIsOnEmulator;
1391}
1392
Andy Hungd1c74342015-07-07 16:54:23 -07001393// static
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001394int MediaPlayerService::AudioOutput::getMinBufferCount()
1395{
Andy Hungd1c74342015-07-07 16:54:23 -07001396 setMinBufferCount(); // benign race wrt other threads
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001397 return mMinBufferCount;
1398}
1399
1400ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1401{
Andy Hungd1c74342015-07-07 16:54:23 -07001402 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001403 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001404 return mTrack->frameCount() * mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001405}
1406
1407ssize_t MediaPlayerService::AudioOutput::frameCount() const
1408{
Andy Hungd1c74342015-07-07 16:54:23 -07001409 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001410 if (mTrack == 0) return NO_INIT;
1411 return mTrack->frameCount();
1412}
1413
1414ssize_t MediaPlayerService::AudioOutput::channelCount() const
1415{
Andy Hungd1c74342015-07-07 16:54:23 -07001416 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001417 if (mTrack == 0) return NO_INIT;
1418 return mTrack->channelCount();
1419}
1420
1421ssize_t MediaPlayerService::AudioOutput::frameSize() const
1422{
Andy Hungd1c74342015-07-07 16:54:23 -07001423 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001424 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001425 return mFrameSize;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001426}
1427
1428uint32_t MediaPlayerService::AudioOutput::latency () const
1429{
Andy Hungd1c74342015-07-07 16:54:23 -07001430 Mutex::Autolock lock(mLock);
Eric Laurentdb354e52012-03-05 17:27:11 -08001431 if (mTrack == 0) return 0;
1432 return mTrack->latency();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001433}
1434
1435float MediaPlayerService::AudioOutput::msecsPerFrame() const
1436{
Andy Hungd1c74342015-07-07 16:54:23 -07001437 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001438 return mMsecsPerFrame;
1439}
1440
Marco Nelissen4110c102012-03-29 09:31:28 -07001441status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position) const
Eric Laurent342e9cf2010-01-19 17:37:09 -08001442{
Andy Hungd1c74342015-07-07 16:54:23 -07001443 Mutex::Autolock lock(mLock);
Eric Laurent342e9cf2010-01-19 17:37:09 -08001444 if (mTrack == 0) return NO_INIT;
1445 return mTrack->getPosition(position);
1446}
1447
Lajos Molnar06ad1522014-08-28 07:27:44 -07001448status_t MediaPlayerService::AudioOutput::getTimestamp(AudioTimestamp &ts) const
1449{
Andy Hungd1c74342015-07-07 16:54:23 -07001450 Mutex::Autolock lock(mLock);
Lajos Molnar06ad1522014-08-28 07:27:44 -07001451 if (mTrack == 0) return NO_INIT;
1452 return mTrack->getTimestamp(ts);
1453}
1454
Marco Nelissen4110c102012-03-29 09:31:28 -07001455status_t MediaPlayerService::AudioOutput::getFramesWritten(uint32_t *frameswritten) const
1456{
Andy Hungd1c74342015-07-07 16:54:23 -07001457 Mutex::Autolock lock(mLock);
Marco Nelissen4110c102012-03-29 09:31:28 -07001458 if (mTrack == 0) return NO_INIT;
Andy Hungd1c74342015-07-07 16:54:23 -07001459 *frameswritten = mBytesWritten / mFrameSize;
Marco Nelissen4110c102012-03-29 09:31:28 -07001460 return OK;
1461}
1462
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001463status_t MediaPlayerService::AudioOutput::setParameters(const String8& keyValuePairs)
1464{
Andy Hungd1c74342015-07-07 16:54:23 -07001465 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001466 if (mTrack == 0) return NO_INIT;
1467 return mTrack->setParameters(keyValuePairs);
1468}
1469
1470String8 MediaPlayerService::AudioOutput::getParameters(const String8& keys)
1471{
Andy Hungd1c74342015-07-07 16:54:23 -07001472 Mutex::Autolock lock(mLock);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001473 if (mTrack == 0) return String8::empty();
1474 return mTrack->getParameters(keys);
1475}
1476
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001477void MediaPlayerService::AudioOutput::setAudioAttributes(const audio_attributes_t * attributes) {
Andy Hungd1c74342015-07-07 16:54:23 -07001478 Mutex::Autolock lock(mLock);
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001479 if (attributes == NULL) {
1480 free(mAttributes);
1481 mAttributes = NULL;
1482 } else {
1483 if (mAttributes == NULL) {
1484 mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1485 }
1486 memcpy(mAttributes, attributes, sizeof(audio_attributes_t));
Eric Laurent43562692015-07-15 16:49:07 -07001487 mStreamType = audio_attributes_to_stream_type(attributes);
1488 }
1489}
1490
1491void MediaPlayerService::AudioOutput::setAudioStreamType(audio_stream_type_t streamType)
1492{
Jean-Michel Trivi2650e962015-07-22 18:14:02 -07001493 Mutex::Autolock lock(mLock);
Eric Laurent43562692015-07-15 16:49:07 -07001494 // do not allow direct stream type modification if attributes have been set
1495 if (mAttributes == NULL) {
1496 mStreamType = streamType;
1497 }
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001498}
1499
Andy Hungd1c74342015-07-07 16:54:23 -07001500void MediaPlayerService::AudioOutput::deleteRecycledTrack_l()
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001501{
Andy Hungd1c74342015-07-07 16:54:23 -07001502 ALOGV("deleteRecycledTrack_l");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001503 if (mRecycledTrack != 0) {
1504
1505 if (mCallbackData != NULL) {
1506 mCallbackData->setOutput(NULL);
1507 mCallbackData->endTrackSwitch();
1508 }
1509
1510 if ((mRecycledTrack->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) {
1511 mRecycledTrack->flush();
1512 }
1513 // An offloaded track isn't flushed because the STREAM_END is reported
1514 // slightly prematurely to allow time for the gapless track switch
1515 // but this means that if we decide not to recycle the track there
1516 // could be a small amount of residual data still playing. We leave
1517 // AudioFlinger to drain the track.
1518
1519 mRecycledTrack.clear();
Andy Hungd1c74342015-07-07 16:54:23 -07001520 close_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001521 delete mCallbackData;
1522 mCallbackData = NULL;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001523 }
1524}
1525
Andy Hungd1c74342015-07-07 16:54:23 -07001526void MediaPlayerService::AudioOutput::close_l()
1527{
1528 mTrack.clear();
1529}
1530
Andreas Huber20111aa2009-07-14 16:56:47 -07001531status_t MediaPlayerService::AudioOutput::open(
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001532 uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
1533 audio_format_t format, int bufferCount,
Eric Laurent1948eb32012-04-13 16:50:19 -07001534 AudioCallback cb, void *cookie,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001535 audio_output_flags_t flags,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001536 const audio_offload_info_t *offloadInfo,
Andy Hung179652e2015-05-31 22:49:46 -07001537 bool doNotReconnect,
1538 uint32_t suggestedFrameCount)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001539{
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001540 ALOGV("open(%u, %d, 0x%x, 0x%x, %d, %d 0x%x)", sampleRate, channelCount, channelMask,
1541 format, bufferCount, mSessionId, flags);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001542
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001543 // offloading is only supported in callback mode for now.
1544 // offloadInfo must be present if offload flag is set
1545 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) &&
1546 ((cb == NULL) || (offloadInfo == NULL))) {
1547 return BAD_VALUE;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001548 }
1549
Andy Hung179652e2015-05-31 22:49:46 -07001550 // compute frame count for the AudioTrack internal buffer
1551 size_t frameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001552 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1553 frameCount = 0; // AudioTrack will get frame count from AudioFlinger
1554 } else {
Andy Hung179652e2015-05-31 22:49:46 -07001555 // try to estimate the buffer processing fetch size from AudioFlinger.
1556 // framesPerBuffer is approximate and generally correct, except when it's not :-).
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001557 uint32_t afSampleRate;
1558 size_t afFrameCount;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001559 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1560 return NO_INIT;
1561 }
1562 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1563 return NO_INIT;
1564 }
Andy Hung179652e2015-05-31 22:49:46 -07001565 const size_t framesPerBuffer =
1566 (unsigned long long)sampleRate * afFrameCount / afSampleRate;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001567
Andy Hung179652e2015-05-31 22:49:46 -07001568 if (bufferCount == 0) {
1569 // use suggestedFrameCount
1570 bufferCount = (suggestedFrameCount + framesPerBuffer - 1) / framesPerBuffer;
1571 }
1572 // Check argument bufferCount against the mininum buffer count
1573 if (bufferCount != 0 && bufferCount < mMinBufferCount) {
1574 ALOGV("bufferCount (%d) increased to %d", bufferCount, mMinBufferCount);
1575 bufferCount = mMinBufferCount;
1576 }
1577 // if frameCount is 0, then AudioTrack will get frame count from AudioFlinger
1578 // which will be the minimum size permitted.
1579 frameCount = bufferCount * framesPerBuffer;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001580 }
Andreas Huber20111aa2009-07-14 16:56:47 -07001581
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001582 if (channelMask == CHANNEL_MASK_USE_CHANNEL_ORDER) {
Glenn Kastenab334fd2012-03-14 12:56:06 -07001583 channelMask = audio_channel_out_mask_from_count(channelCount);
Jean-Michel Trivi786618f2012-03-02 14:54:07 -08001584 if (0 == channelMask) {
1585 ALOGE("open() error, can\'t derive mask for %d audio channels", channelCount);
1586 return NO_INIT;
1587 }
1588 }
Eric Laurent1948eb32012-04-13 16:50:19 -07001589
Andy Hungd1c74342015-07-07 16:54:23 -07001590 Mutex::Autolock lock(mLock);
Andy Hung179652e2015-05-31 22:49:46 -07001591 mCallback = cb;
1592 mCallbackCookie = cookie;
1593
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001594 // Check whether we can recycle the track
1595 bool reuse = false;
1596 bool bothOffloaded = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001597
Glenn Kasten2799d742013-05-30 14:33:29 -07001598 if (mRecycledTrack != 0) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001599 // check whether we are switching between two offloaded tracks
1600 bothOffloaded = (flags & mRecycledTrack->getFlags()
1601 & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0;
Marco Nelissen67295b52012-06-11 14:52:53 -07001602
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001603 // check if the existing track can be reused as-is, or if a new track needs to be created.
1604 reuse = true;
1605
Marco Nelissen67295b52012-06-11 14:52:53 -07001606 if ((mCallbackData == NULL && mCallback != NULL) ||
1607 (mCallbackData != NULL && mCallback == NULL)) {
1608 // recycled track uses callbacks but the caller wants to use writes, or vice versa
1609 ALOGV("can't chain callback and write");
1610 reuse = false;
1611 } else if ((mRecycledTrack->getSampleRate() != sampleRate) ||
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001612 (mRecycledTrack->channelCount() != (uint32_t)channelCount) ) {
1613 ALOGV("samplerate, channelcount differ: %u/%u Hz, %u/%d ch",
Marco Nelissen67295b52012-06-11 14:52:53 -07001614 mRecycledTrack->getSampleRate(), sampleRate,
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001615 mRecycledTrack->channelCount(), channelCount);
Marco Nelissen67295b52012-06-11 14:52:53 -07001616 reuse = false;
1617 } else if (flags != mFlags) {
1618 ALOGV("output flags differ %08x/%08x", flags, mFlags);
1619 reuse = false;
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001620 } else if (mRecycledTrack->format() != format) {
1621 reuse = false;
Marco Nelissen67295b52012-06-11 14:52:53 -07001622 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001623 } else {
1624 ALOGV("no track available to recycle");
1625 }
1626
1627 ALOGV_IF(bothOffloaded, "both tracks offloaded");
1628
1629 // If we can't recycle and both tracks are offloaded
1630 // we must close the previous output before opening a new one
1631 if (bothOffloaded && !reuse) {
1632 ALOGV("both offloaded and not recycling");
Andy Hungd1c74342015-07-07 16:54:23 -07001633 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001634 }
1635
1636 sp<AudioTrack> t;
1637 CallbackData *newcbd = NULL;
1638
1639 // We don't attempt to create a new track if we are recycling an
1640 // offloaded track. But, if we are recycling a non-offloaded or we
1641 // are switching where one is offloaded and one isn't then we create
1642 // the new track in advance so that we can read additional stream info
1643
1644 if (!(reuse && bothOffloaded)) {
1645 ALOGV("creating new AudioTrack");
1646
1647 if (mCallback != NULL) {
1648 newcbd = new CallbackData(this);
1649 t = new AudioTrack(
1650 mStreamType,
1651 sampleRate,
1652 format,
1653 channelMask,
1654 frameCount,
1655 flags,
1656 CallbackWrapper,
1657 newcbd,
1658 0, // notification frames
1659 mSessionId,
1660 AudioTrack::TRANSFER_CALLBACK,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001661 offloadInfo,
Marco Nelissend457c972014-02-11 08:47:07 -08001662 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001663 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001664 mAttributes,
1665 doNotReconnect);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001666 } else {
1667 t = new AudioTrack(
1668 mStreamType,
1669 sampleRate,
1670 format,
1671 channelMask,
1672 frameCount,
1673 flags,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001674 NULL, // callback
1675 NULL, // user data
1676 0, // notification frames
1677 mSessionId,
1678 AudioTrack::TRANSFER_DEFAULT,
1679 NULL, // offload info
Marco Nelissend457c972014-02-11 08:47:07 -08001680 mUid,
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001681 mPid,
Ronghua Wufaeb0f22015-05-21 12:20:21 -07001682 mAttributes,
1683 doNotReconnect);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001684 }
1685
1686 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1687 ALOGE("Unable to create audio track");
1688 delete newcbd;
Glenn Kasten3e98ecd2015-05-18 13:13:24 -07001689 // t goes out of scope, so reference count drops to zero
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001690 return NO_INIT;
Jean-Michel Trivid9d7fa02014-06-24 08:01:46 -07001691 } else {
1692 // successful AudioTrack initialization implies a legacy stream type was generated
1693 // from the audio attributes
1694 mStreamType = t->streamType();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001695 }
1696 }
1697
1698 if (reuse) {
1699 CHECK(mRecycledTrack != NULL);
1700
1701 if (!bothOffloaded) {
1702 if (mRecycledTrack->frameCount() != t->frameCount()) {
1703 ALOGV("framecount differs: %u/%u frames",
1704 mRecycledTrack->frameCount(), t->frameCount());
1705 reuse = false;
1706 }
1707 }
1708
Marco Nelissen67295b52012-06-11 14:52:53 -07001709 if (reuse) {
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001710 ALOGV("chaining to next output and recycling track");
Andy Hungd1c74342015-07-07 16:54:23 -07001711 close_l();
Marco Nelissen67295b52012-06-11 14:52:53 -07001712 mTrack = mRecycledTrack;
Glenn Kasten2799d742013-05-30 14:33:29 -07001713 mRecycledTrack.clear();
Marco Nelissen67295b52012-06-11 14:52:53 -07001714 if (mCallbackData != NULL) {
1715 mCallbackData->setOutput(this);
1716 }
Marco Nelissen67295b52012-06-11 14:52:53 -07001717 delete newcbd;
1718 return OK;
1719 }
Marco Nelissen67295b52012-06-11 14:52:53 -07001720 }
1721
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001722 // we're not going to reuse the track, unblock and flush it
1723 // this was done earlier if both tracks are offloaded
1724 if (!bothOffloaded) {
Andy Hungd1c74342015-07-07 16:54:23 -07001725 deleteRecycledTrack_l();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001726 }
1727
1728 CHECK((t != NULL) && ((mCallback == NULL) || (newcbd != NULL)));
1729
Marco Nelissen67295b52012-06-11 14:52:53 -07001730 mCallbackData = newcbd;
Steve Block3856b092011-10-20 11:56:00 +01001731 ALOGV("setVolume");
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001732 t->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07001733
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001734 mSampleRateHz = sampleRate;
Preetam Singh Ranawat2e17eef2015-08-12 12:11:46 -07001735 mFlags = flags;
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001736 mMsecsPerFrame = 1E3f / (mPlaybackRate.mSpeed * sampleRate);
Andy Hungd1c74342015-07-07 16:54:23 -07001737 mFrameSize = t->frameSize();
Marco Nelissen99448602012-04-02 12:16:49 -07001738 uint32_t pos;
1739 if (t->getPosition(&pos) == OK) {
Andy Hungd1c74342015-07-07 16:54:23 -07001740 mBytesWritten = uint64_t(pos) * mFrameSize;
Marco Nelissen99448602012-04-02 12:16:49 -07001741 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001742 mTrack = t;
Eric Laurent2beeb502010-07-16 07:43:46 -07001743
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001744 status_t res = NO_ERROR;
Wei Jia0162d002015-06-09 11:59:33 -07001745 // Note some output devices may give us a direct track even though we don't specify it.
1746 // Example: Line application b/17459982.
Preetam Singh Ranawat2e17eef2015-08-12 12:11:46 -07001747 if ((t->getFlags() & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) {
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001748 res = t->setPlaybackRate(mPlaybackRate);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001749 if (res == NO_ERROR) {
1750 t->setAuxEffectSendLevel(mSendLevel);
1751 res = t->attachAuxEffect(mAuxEffectId);
1752 }
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001753 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001754 ALOGV("open() DONE status %d", res);
1755 return res;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001756}
1757
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001758status_t MediaPlayerService::AudioOutput::start()
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001759{
Steve Block3856b092011-10-20 11:56:00 +01001760 ALOGV("start");
Andy Hungd1c74342015-07-07 16:54:23 -07001761 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001762 if (mCallbackData != NULL) {
1763 mCallbackData->endTrackSwitch();
1764 }
Glenn Kasten2799d742013-05-30 14:33:29 -07001765 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001766 mTrack->setVolume(mLeftVolume, mRightVolume);
Eric Laurent2beeb502010-07-16 07:43:46 -07001767 mTrack->setAuxEffectSendLevel(mSendLevel);
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001768 return mTrack->start();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001769 }
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001770 return NO_INIT;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001771}
1772
Marco Nelissen6b74d672012-02-28 16:07:44 -08001773void MediaPlayerService::AudioOutput::setNextOutput(const sp<AudioOutput>& nextOutput) {
Andy Hungd1c74342015-07-07 16:54:23 -07001774 Mutex::Autolock lock(mLock);
Marco Nelissen6b74d672012-02-28 16:07:44 -08001775 mNextOutput = nextOutput;
1776}
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08001777
Marco Nelissen6b74d672012-02-28 16:07:44 -08001778void MediaPlayerService::AudioOutput::switchToNextOutput() {
1779 ALOGV("switchToNextOutput");
Andy Hungd1c74342015-07-07 16:54:23 -07001780
1781 // Try to acquire the callback lock before moving track (without incurring deadlock).
1782 const unsigned kMaxSwitchTries = 100;
1783 Mutex::Autolock lock(mLock);
1784 for (unsigned tries = 0;;) {
1785 if (mTrack == 0) {
1786 return;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001787 }
Andy Hungd1c74342015-07-07 16:54:23 -07001788 if (mNextOutput != NULL && mNextOutput != this) {
1789 if (mCallbackData != NULL) {
1790 // two alternative approaches
1791#if 1
1792 CallbackData *callbackData = mCallbackData;
1793 mLock.unlock();
1794 // proper acquisition sequence
1795 callbackData->lock();
1796 mLock.lock();
1797 // Caution: it is unlikely that someone deleted our callback or changed our target
1798 if (callbackData != mCallbackData || mNextOutput == NULL || mNextOutput == this) {
1799 // fatal if we are starved out.
1800 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
1801 "switchToNextOutput() cannot obtain correct lock sequence");
1802 callbackData->unlock();
1803 continue;
1804 }
1805 callbackData->mSwitching = true; // begin track switch
1806#else
1807 // tryBeginTrackSwitch() returns false if the callback has the lock.
1808 if (!mCallbackData->tryBeginTrackSwitch()) {
1809 // fatal if we are starved out.
1810 LOG_ALWAYS_FATAL_IF(++tries > kMaxSwitchTries,
1811 "switchToNextOutput() cannot obtain callback lock");
1812 mLock.unlock();
1813 usleep(5 * 1000 /* usec */); // allow callback to use AudioOutput
1814 mLock.lock();
1815 continue;
1816 }
1817#endif
1818 }
1819
1820 Mutex::Autolock nextLock(mNextOutput->mLock);
1821
1822 // If the next output track is not NULL, then it has been
1823 // opened already for playback.
1824 // This is possible even without the next player being started,
1825 // for example, the next player could be prepared and seeked.
1826 //
1827 // Presuming it isn't advisable to force the track over.
1828 if (mNextOutput->mTrack == NULL) {
1829 ALOGD("Recycling track for gapless playback");
1830 delete mNextOutput->mCallbackData;
1831 mNextOutput->mCallbackData = mCallbackData;
1832 mNextOutput->mRecycledTrack = mTrack;
1833 mNextOutput->mSampleRateHz = mSampleRateHz;
1834 mNextOutput->mMsecsPerFrame = mMsecsPerFrame;
1835 mNextOutput->mBytesWritten = mBytesWritten;
1836 mNextOutput->mFlags = mFlags;
1837 mNextOutput->mFrameSize = mFrameSize;
1838 close_l();
1839 mCallbackData = NULL; // destruction handled by mNextOutput
1840 } else {
1841 ALOGW("Ignoring gapless playback because next player has already started");
1842 // remove track in case resource needed for future players.
1843 if (mCallbackData != NULL) {
1844 mCallbackData->endTrackSwitch(); // release lock for callbacks before close.
1845 }
1846 close_l();
1847 }
1848 }
1849 break;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001850 }
1851}
1852
Wei Jia7d3f4df2015-03-03 15:28:00 -08001853ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size, bool blocking)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001854{
Andy Hungd1c74342015-07-07 16:54:23 -07001855 Mutex::Autolock lock(mLock);
Glenn Kastenadad3d72014-02-21 14:51:43 -08001856 LOG_ALWAYS_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
Andreas Huber20111aa2009-07-14 16:56:47 -07001857
Steve Block3856b092011-10-20 11:56:00 +01001858 //ALOGV("write(%p, %u)", buffer, size);
Glenn Kasten2799d742013-05-30 14:33:29 -07001859 if (mTrack != 0) {
Wei Jia7d3f4df2015-03-03 15:28:00 -08001860 ssize_t ret = mTrack->write(buffer, size, blocking);
Andy Hunga31335a2014-08-20 17:37:59 -07001861 if (ret >= 0) {
1862 mBytesWritten += ret;
1863 }
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001864 return ret;
1865 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001866 return NO_INIT;
1867}
1868
1869void MediaPlayerService::AudioOutput::stop()
1870{
Steve Block3856b092011-10-20 11:56:00 +01001871 ALOGV("stop");
Andy Hungd1c74342015-07-07 16:54:23 -07001872 Mutex::Autolock lock(mLock);
Andy Hungda17c042015-06-01 15:53:14 -07001873 mBytesWritten = 0;
Glenn Kasten2799d742013-05-30 14:33:29 -07001874 if (mTrack != 0) mTrack->stop();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001875}
1876
1877void MediaPlayerService::AudioOutput::flush()
1878{
Steve Block3856b092011-10-20 11:56:00 +01001879 ALOGV("flush");
Andy Hungd1c74342015-07-07 16:54:23 -07001880 Mutex::Autolock lock(mLock);
Andy Hungda17c042015-06-01 15:53:14 -07001881 mBytesWritten = 0;
Glenn Kasten2799d742013-05-30 14:33:29 -07001882 if (mTrack != 0) mTrack->flush();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001883}
1884
1885void MediaPlayerService::AudioOutput::pause()
1886{
Steve Block3856b092011-10-20 11:56:00 +01001887 ALOGV("pause");
Andy Hungd1c74342015-07-07 16:54:23 -07001888 Mutex::Autolock lock(mLock);
Glenn Kasten2799d742013-05-30 14:33:29 -07001889 if (mTrack != 0) mTrack->pause();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001890}
1891
1892void MediaPlayerService::AudioOutput::close()
1893{
Steve Block3856b092011-10-20 11:56:00 +01001894 ALOGV("close");
Andy Hungd1c74342015-07-07 16:54:23 -07001895 Mutex::Autolock lock(mLock);
1896 close_l();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001897}
1898
1899void MediaPlayerService::AudioOutput::setVolume(float left, float right)
1900{
Steve Block3856b092011-10-20 11:56:00 +01001901 ALOGV("setVolume(%f, %f)", left, right);
Andy Hungd1c74342015-07-07 16:54:23 -07001902 Mutex::Autolock lock(mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001903 mLeftVolume = left;
1904 mRightVolume = right;
Glenn Kasten2799d742013-05-30 14:33:29 -07001905 if (mTrack != 0) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001906 mTrack->setVolume(left, right);
1907 }
1908}
1909
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001910status_t MediaPlayerService::AudioOutput::setPlaybackRate(const AudioPlaybackRate &rate)
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001911{
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001912 ALOGV("setPlaybackRate(%f %f %d %d)",
1913 rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Andy Hungd1c74342015-07-07 16:54:23 -07001914 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001915 if (mTrack == 0) {
1916 // remember rate so that we can set it when the track is opened
1917 mPlaybackRate = rate;
1918 return OK;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001919 }
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001920 status_t res = mTrack->setPlaybackRate(rate);
1921 if (res != NO_ERROR) {
1922 return res;
1923 }
1924 // rate.mSpeed is always greater than 0 if setPlaybackRate succeeded
1925 CHECK_GT(rate.mSpeed, 0.f);
1926 mPlaybackRate = rate;
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001927 if (mSampleRateHz != 0) {
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001928 mMsecsPerFrame = 1E3f / (rate.mSpeed * mSampleRateHz);
Jean-Michel Trivi7a8b0ed2012-02-02 09:06:31 -08001929 }
1930 return res;
1931}
1932
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001933status_t MediaPlayerService::AudioOutput::getPlaybackRate(AudioPlaybackRate *rate)
1934{
1935 ALOGV("setPlaybackRate");
Andy Hungd1c74342015-07-07 16:54:23 -07001936 Mutex::Autolock lock(mLock);
Lajos Molnar3a474aa2015-04-24 17:10:07 -07001937 if (mTrack == 0) {
1938 return NO_INIT;
1939 }
1940 *rate = mTrack->getPlaybackRate();
1941 return NO_ERROR;
1942}
1943
Eric Laurent2beeb502010-07-16 07:43:46 -07001944status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
1945{
Steve Block3856b092011-10-20 11:56:00 +01001946 ALOGV("setAuxEffectSendLevel(%f)", level);
Andy Hungd1c74342015-07-07 16:54:23 -07001947 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07001948 mSendLevel = level;
Glenn Kasten2799d742013-05-30 14:33:29 -07001949 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07001950 return mTrack->setAuxEffectSendLevel(level);
1951 }
1952 return NO_ERROR;
1953}
1954
1955status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
1956{
Steve Block3856b092011-10-20 11:56:00 +01001957 ALOGV("attachAuxEffect(%d)", effectId);
Andy Hungd1c74342015-07-07 16:54:23 -07001958 Mutex::Autolock lock(mLock);
Eric Laurent2beeb502010-07-16 07:43:46 -07001959 mAuxEffectId = effectId;
Glenn Kasten2799d742013-05-30 14:33:29 -07001960 if (mTrack != 0) {
Eric Laurent2beeb502010-07-16 07:43:46 -07001961 return mTrack->attachAuxEffect(effectId);
1962 }
1963 return NO_ERROR;
1964}
1965
Andreas Huber20111aa2009-07-14 16:56:47 -07001966// static
1967void MediaPlayerService::AudioOutput::CallbackWrapper(
Glenn Kastend217a8c2011-06-01 15:20:35 -07001968 int event, void *cookie, void *info) {
Steve Block3856b092011-10-20 11:56:00 +01001969 //ALOGV("callbackwrapper");
Marco Nelissen6b74d672012-02-28 16:07:44 -08001970 CallbackData *data = (CallbackData*)cookie;
Andy Hungd1c74342015-07-07 16:54:23 -07001971 // lock to ensure we aren't caught in the middle of a track switch.
Marco Nelissen6b74d672012-02-28 16:07:44 -08001972 data->lock();
1973 AudioOutput *me = data->getOutput();
Andreas Huber20111aa2009-07-14 16:56:47 -07001974 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
Marco Nelissen6b74d672012-02-28 16:07:44 -08001975 if (me == NULL) {
1976 // no output set, likely because the track was scheduled to be reused
1977 // by another player, but the format turned out to be incompatible.
1978 data->unlock();
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001979 if (buffer != NULL) {
1980 buffer->size = 0;
1981 }
Marco Nelissen6b74d672012-02-28 16:07:44 -08001982 return;
1983 }
Andreas Huber20111aa2009-07-14 16:56:47 -07001984
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01001985 switch(event) {
1986 case AudioTrack::EVENT_MORE_DATA: {
1987 size_t actualSize = (*me->mCallback)(
1988 me, buffer->raw, buffer->size, me->mCallbackCookie,
1989 CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08001990
Andy Hung719b46b2015-05-31 22:18:25 -07001991 // Log when no data is returned from the callback.
1992 // (1) We may have no data (especially with network streaming sources).
1993 // (2) We may have reached the EOS and the audio track is not stopped yet.
1994 // Note that AwesomePlayer/AudioPlayer will only return zero size when it reaches the EOS.
1995 // NuPlayerRenderer will return zero when it doesn't have data (it doesn't block to fill).
1996 //
1997 // This is a benign busy-wait, with the next data request generated 10 ms or more later;
1998 // nevertheless for power reasons, we don't want to see too many of these.
Andreas Huber2e8ffaf2010-02-18 16:45:13 -08001999
Andy Hung719b46b2015-05-31 22:18:25 -07002000 ALOGV_IF(actualSize == 0 && buffer->size > 0, "callbackwrapper: empty buffer returned");
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002001
Andy Hung719b46b2015-05-31 22:18:25 -07002002 me->mBytesWritten += actualSize; // benign race with reader.
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002003 buffer->size = actualSize;
2004 } break;
2005
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002006 case AudioTrack::EVENT_STREAM_END:
Andy Hung719b46b2015-05-31 22:18:25 -07002007 // currently only occurs for offloaded callbacks
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002008 ALOGV("callbackwrapper: deliver EVENT_STREAM_END");
2009 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2010 me->mCallbackCookie, CB_EVENT_STREAM_END);
2011 break;
2012
2013 case AudioTrack::EVENT_NEW_IAUDIOTRACK :
2014 ALOGV("callbackwrapper: deliver EVENT_TEAR_DOWN");
2015 (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
2016 me->mCallbackCookie, CB_EVENT_TEAR_DOWN);
2017 break;
2018
Glenn Kasten421743b2015-06-01 08:18:08 -07002019 case AudioTrack::EVENT_UNDERRUN:
Andy Hung719b46b2015-05-31 22:18:25 -07002020 // This occurs when there is no data available, typically
Glenn Kasten421743b2015-06-01 08:18:08 -07002021 // when there is a failure to supply data to the AudioTrack. It can also
2022 // occur in non-offloaded mode when the audio device comes out of standby.
2023 //
Andy Hung719b46b2015-05-31 22:18:25 -07002024 // If an AudioTrack underruns it outputs silence. Since this happens suddenly
2025 // it may sound like an audible pop or glitch.
2026 //
2027 // The underrun event is sent once per track underrun; the condition is reset
2028 // when more data is sent to the AudioTrack.
Glenn Kasten421743b2015-06-01 08:18:08 -07002029 ALOGI("callbackwrapper: EVENT_UNDERRUN (discarded)");
2030 break;
2031
Richard Fitzgeraldd89532e2013-05-14 13:18:21 +01002032 default:
2033 ALOGE("received unknown event type: %d inside CallbackWrapper !", event);
Andreas Huber51c1e0e2011-04-04 11:43:40 -07002034 }
2035
Marco Nelissen6b74d672012-02-28 16:07:44 -08002036 data->unlock();
Andreas Huber20111aa2009-07-14 16:56:47 -07002037}
2038
Marco Nelissen4110c102012-03-29 09:31:28 -07002039int MediaPlayerService::AudioOutput::getSessionId() const
Eric Laurent8c563ed2010-10-07 18:23:03 -07002040{
Andy Hungd1c74342015-07-07 16:54:23 -07002041 Mutex::Autolock lock(mLock);
Eric Laurent8c563ed2010-10-07 18:23:03 -07002042 return mSessionId;
2043}
2044
Eric Laurent6f59db12013-07-26 17:16:50 -07002045uint32_t MediaPlayerService::AudioOutput::getSampleRate() const
2046{
Andy Hungd1c74342015-07-07 16:54:23 -07002047 Mutex::Autolock lock(mLock);
Eric Laurent6f59db12013-07-26 17:16:50 -07002048 if (mTrack == 0) return 0;
2049 return mTrack->getSampleRate();
2050}
2051
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002052////////////////////////////////////////////////////////////////////////////////
2053
2054struct CallbackThread : public Thread {
2055 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
2056 MediaPlayerBase::AudioSink::AudioCallback cb,
2057 void *cookie);
2058
2059protected:
2060 virtual ~CallbackThread();
2061
2062 virtual bool threadLoop();
2063
2064private:
2065 wp<MediaPlayerBase::AudioSink> mSink;
2066 MediaPlayerBase::AudioSink::AudioCallback mCallback;
2067 void *mCookie;
2068 void *mBuffer;
2069 size_t mBufferSize;
2070
2071 CallbackThread(const CallbackThread &);
2072 CallbackThread &operator=(const CallbackThread &);
2073};
2074
2075CallbackThread::CallbackThread(
2076 const wp<MediaPlayerBase::AudioSink> &sink,
2077 MediaPlayerBase::AudioSink::AudioCallback cb,
2078 void *cookie)
2079 : mSink(sink),
2080 mCallback(cb),
2081 mCookie(cookie),
2082 mBuffer(NULL),
2083 mBufferSize(0) {
2084}
2085
2086CallbackThread::~CallbackThread() {
2087 if (mBuffer) {
2088 free(mBuffer);
2089 mBuffer = NULL;
2090 }
2091}
2092
2093bool CallbackThread::threadLoop() {
2094 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
2095 if (sink == NULL) {
2096 return false;
2097 }
2098
2099 if (mBuffer == NULL) {
2100 mBufferSize = sink->bufferSize();
2101 mBuffer = malloc(mBufferSize);
2102 }
2103
2104 size_t actualSize =
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002105 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie,
2106 MediaPlayerBase::AudioSink::CB_EVENT_FILL_BUFFER);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002107
2108 if (actualSize > 0) {
2109 sink->write(mBuffer, actualSize);
Andy Hunga31335a2014-08-20 17:37:59 -07002110 // Could return false on sink->write() error or short count.
2111 // Not necessarily appropriate but would work for AudioCache behavior.
Andreas Huber7d5b8a72010-02-09 16:59:18 -08002112 }
2113
2114 return true;
2115}
2116
2117////////////////////////////////////////////////////////////////////////////////
2118
Gloria Wang7cf180c2011-02-19 18:37:57 -08002119void MediaPlayerService::addBatteryData(uint32_t params)
2120{
2121 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002122
2123 int32_t time = systemTime() / 1000000L;
2124
2125 // change audio output devices. This notification comes from AudioFlinger
2126 if ((params & kBatteryDataSpeakerOn)
2127 || (params & kBatteryDataOtherAudioDeviceOn)) {
2128
2129 int deviceOn[NUM_AUDIO_DEVICES];
2130 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2131 deviceOn[i] = 0;
2132 }
2133
2134 if ((params & kBatteryDataSpeakerOn)
2135 && (params & kBatteryDataOtherAudioDeviceOn)) {
2136 deviceOn[SPEAKER_AND_OTHER] = 1;
2137 } else if (params & kBatteryDataSpeakerOn) {
2138 deviceOn[SPEAKER] = 1;
2139 } else {
2140 deviceOn[OTHER_AUDIO_DEVICE] = 1;
2141 }
2142
2143 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2144 if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
2145
2146 if (mBatteryAudio.refCount > 0) { // if playing audio
2147 if (!deviceOn[i]) {
2148 mBatteryAudio.lastTime[i] += time;
2149 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2150 mBatteryAudio.lastTime[i] = 0;
2151 } else {
2152 mBatteryAudio.lastTime[i] = 0 - time;
2153 }
2154 }
2155
2156 mBatteryAudio.deviceOn[i] = deviceOn[i];
2157 }
2158 }
2159 return;
2160 }
2161
Marco Nelissenb7848f12014-12-04 08:57:56 -08002162 // an audio stream is started
Gloria Wang9ee159b2011-02-24 14:51:45 -08002163 if (params & kBatteryDataAudioFlingerStart) {
2164 // record the start time only if currently no other audio
2165 // is being played
2166 if (mBatteryAudio.refCount == 0) {
2167 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2168 if (mBatteryAudio.deviceOn[i]) {
2169 mBatteryAudio.lastTime[i] -= time;
2170 }
2171 }
2172 }
2173
2174 mBatteryAudio.refCount ++;
2175 return;
2176
2177 } else if (params & kBatteryDataAudioFlingerStop) {
2178 if (mBatteryAudio.refCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002179 ALOGW("Battery track warning: refCount is <= 0");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002180 return;
2181 }
2182
2183 // record the stop time only if currently this is the only
2184 // audio being played
2185 if (mBatteryAudio.refCount == 1) {
2186 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2187 if (mBatteryAudio.deviceOn[i]) {
2188 mBatteryAudio.lastTime[i] += time;
2189 mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
2190 mBatteryAudio.lastTime[i] = 0;
2191 }
2192 }
2193 }
2194
2195 mBatteryAudio.refCount --;
2196 return;
2197 }
2198
Gloria Wang7cf180c2011-02-19 18:37:57 -08002199 int uid = IPCThreadState::self()->getCallingUid();
2200 if (uid == AID_MEDIA) {
2201 return;
2202 }
2203 int index = mBatteryData.indexOfKey(uid);
Gloria Wang7cf180c2011-02-19 18:37:57 -08002204
2205 if (index < 0) { // create a new entry for this UID
2206 BatteryUsageInfo info;
2207 info.audioTotalTime = 0;
2208 info.videoTotalTime = 0;
2209 info.audioLastTime = 0;
2210 info.videoLastTime = 0;
2211 info.refCount = 0;
2212
Gloria Wang9ee159b2011-02-24 14:51:45 -08002213 if (mBatteryData.add(uid, info) == NO_MEMORY) {
Steve Block29357bc2012-01-06 19:20:56 +00002214 ALOGE("Battery track error: no memory for new app");
Gloria Wang9ee159b2011-02-24 14:51:45 -08002215 return;
2216 }
Gloria Wang7cf180c2011-02-19 18:37:57 -08002217 }
2218
2219 BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
2220
2221 if (params & kBatteryDataCodecStarted) {
2222 if (params & kBatteryDataTrackAudio) {
2223 info.audioLastTime -= time;
2224 info.refCount ++;
2225 }
2226 if (params & kBatteryDataTrackVideo) {
2227 info.videoLastTime -= time;
2228 info.refCount ++;
2229 }
2230 } else {
2231 if (info.refCount == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002232 ALOGW("Battery track warning: refCount is already 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002233 return;
2234 } else if (info.refCount < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00002235 ALOGE("Battery track error: refCount < 0");
Gloria Wang7cf180c2011-02-19 18:37:57 -08002236 mBatteryData.removeItem(uid);
2237 return;
2238 }
2239
2240 if (params & kBatteryDataTrackAudio) {
2241 info.audioLastTime += time;
2242 info.refCount --;
2243 }
2244 if (params & kBatteryDataTrackVideo) {
2245 info.videoLastTime += time;
2246 info.refCount --;
2247 }
2248
2249 // no stream is being played by this UID
2250 if (info.refCount == 0) {
2251 info.audioTotalTime += info.audioLastTime;
2252 info.audioLastTime = 0;
2253 info.videoTotalTime += info.videoLastTime;
2254 info.videoLastTime = 0;
2255 }
2256 }
2257}
2258
2259status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
2260 Mutex::Autolock lock(mLock);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002261
2262 // audio output devices usage
2263 int32_t time = systemTime() / 1000000L; //in ms
2264 int32_t totalTime;
2265
2266 for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2267 totalTime = mBatteryAudio.totalTime[i];
2268
2269 if (mBatteryAudio.deviceOn[i]
2270 && (mBatteryAudio.lastTime[i] != 0)) {
2271 int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
2272 totalTime += tmpTime;
2273 }
2274
2275 reply->writeInt32(totalTime);
2276 // reset the total time
2277 mBatteryAudio.totalTime[i] = 0;
2278 }
2279
2280 // codec usage
Gloria Wang7cf180c2011-02-19 18:37:57 -08002281 BatteryUsageInfo info;
2282 int size = mBatteryData.size();
2283
2284 reply->writeInt32(size);
2285 int i = 0;
2286
2287 while (i < size) {
2288 info = mBatteryData.valueAt(i);
2289
2290 reply->writeInt32(mBatteryData.keyAt(i)); //UID
2291 reply->writeInt32(info.audioTotalTime);
2292 reply->writeInt32(info.videoTotalTime);
2293
2294 info.audioTotalTime = 0;
2295 info.videoTotalTime = 0;
2296
2297 // remove the UID entry where no stream is being played
2298 if (info.refCount <= 0) {
2299 mBatteryData.removeItemsAt(i);
2300 size --;
2301 i --;
2302 }
2303 i++;
2304 }
2305 return NO_ERROR;
2306}
nikoa64c8c72009-07-20 15:07:26 -07002307} // namespace android