blob: 82d5c146601468e5c761e4af46e5af4437ae356c [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>
26#include <dirent.h>
27#include <unistd.h>
28
29#include <string.h>
Mathias Agopian6f74b0c2009-06-03 17:32:49 -070030
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080031#include <cutils/atomic.h>
Nicolas Catania14d27472009-07-13 14:37:49 -070032#include <cutils/properties.h> // for property_get
Mathias Agopian6f74b0c2009-06-03 17:32:49 -070033
34#include <utils/misc.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080035
36#include <android_runtime/ActivityManager.h>
Mathias Agopian6f74b0c2009-06-03 17:32:49 -070037
Mathias Agopian75624082009-05-19 19:08:10 -070038#include <binder/IPCThreadState.h>
39#include <binder/IServiceManager.h>
40#include <binder/MemoryHeapBase.h>
41#include <binder/MemoryBase.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>
Nicolas Catania1d187f12009-05-12 23:25:55 -070045#include <utils/Vector.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080046#include <cutils/properties.h>
47
48#include <media/MediaPlayerInterface.h>
49#include <media/mediarecorder.h>
50#include <media/MediaMetadataRetrieverInterface.h>
nikoa64c8c72009-07-20 15:07:26 -070051#include <media/Metadata.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080052#include <media/AudioTrack.h>
53
54#include "MediaRecorderClient.h"
55#include "MediaPlayerService.h"
56#include "MetadataRetrieverClient.h"
57
58#include "MidiFile.h"
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080059#include <media/PVPlayer.h>
Nicolas Catania14d27472009-07-13 14:37:49 -070060#include "TestPlayerStub.h"
Andreas Huber20111aa2009-07-14 16:56:47 -070061#include "StagefrightPlayer.h"
Andreas Huber20111aa2009-07-14 16:56:47 -070062
Andreas Huber20111aa2009-07-14 16:56:47 -070063#include <OMX.h>
Nicolas Catania14d27472009-07-13 14:37:49 -070064
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080065/* desktop Linux needs a little help with gettid() */
66#if defined(HAVE_GETTID) && !defined(HAVE_ANDROID_OS)
67#define __KERNEL__
68# include <linux/unistd.h>
69#ifdef _syscall0
70_syscall0(pid_t,gettid)
71#else
72pid_t gettid() { return syscall(__NR_gettid);}
73#endif
74#undef __KERNEL__
75#endif
76
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070077namespace {
nikoa64c8c72009-07-20 15:07:26 -070078using android::media::Metadata;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070079using android::status_t;
80using android::OK;
81using android::BAD_VALUE;
82using android::NOT_ENOUGH_DATA;
83using android::Parcel;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070084
85// Max number of entries in the filter.
86const int kMaxFilterSize = 64; // I pulled that out of thin air.
87
nikoa64c8c72009-07-20 15:07:26 -070088// FIXME: Move all the metadata related function in the Metadata.cpp
nikod608a812009-07-16 16:39:53 -070089
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070090
91// Unmarshall a filter from a Parcel.
92// Filter format in a parcel:
93//
94// 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
95// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
96// | number of entries (n) |
97// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
98// | metadata type 1 |
99// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
100// | metadata type 2 |
101// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
102// ....
103// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
104// | metadata type n |
105// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
106//
107// @param p Parcel that should start with a filter.
108// @param[out] filter On exit contains the list of metadata type to be
109// filtered.
110// @param[out] status On exit contains the status code to be returned.
111// @return true if the parcel starts with a valid filter.
112bool unmarshallFilter(const Parcel& p,
nikoa64c8c72009-07-20 15:07:26 -0700113 Metadata::Filter *filter,
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700114 status_t *status)
115{
Nicolas Catania48290382009-07-10 13:53:06 -0700116 int32_t val;
117 if (p.readInt32(&val) != OK)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700118 {
119 LOGE("Failed to read filter's length");
120 *status = NOT_ENOUGH_DATA;
121 return false;
122 }
123
Nicolas Catania48290382009-07-10 13:53:06 -0700124 if( val > kMaxFilterSize || val < 0)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700125 {
Nicolas Catania48290382009-07-10 13:53:06 -0700126 LOGE("Invalid filter len %d", val);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700127 *status = BAD_VALUE;
128 return false;
129 }
130
Nicolas Catania48290382009-07-10 13:53:06 -0700131 const size_t num = val;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700132
133 filter->clear();
Nicolas Catania48290382009-07-10 13:53:06 -0700134 filter->setCapacity(num);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700135
nikoa64c8c72009-07-20 15:07:26 -0700136 size_t size = num * sizeof(Metadata::Type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700137
Nicolas Catania48290382009-07-10 13:53:06 -0700138
139 if (p.dataAvail() < size)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700140 {
Nicolas Catania48290382009-07-10 13:53:06 -0700141 LOGE("Filter too short expected %d but got %d", size, p.dataAvail());
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700142 *status = NOT_ENOUGH_DATA;
143 return false;
144 }
145
nikoa64c8c72009-07-20 15:07:26 -0700146 const Metadata::Type *data =
147 static_cast<const Metadata::Type*>(p.readInplace(size));
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700148
Nicolas Catania48290382009-07-10 13:53:06 -0700149 if (NULL == data)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700150 {
151 LOGE("Filter had no data");
152 *status = BAD_VALUE;
153 return false;
154 }
155
156 // TODO: The stl impl of vector would be more efficient here
157 // because it degenerates into a memcpy on pod types. Try to
158 // replace later or use stl::set.
Nicolas Catania48290382009-07-10 13:53:06 -0700159 for (size_t i = 0; i < num; ++i)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700160 {
Nicolas Catania48290382009-07-10 13:53:06 -0700161 filter->add(*data);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700162 ++data;
163 }
164 *status = OK;
165 return true;
166}
167
Nicolas Catania48290382009-07-10 13:53:06 -0700168// @param filter Of metadata type.
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700169// @param val To be searched.
170// @return true if a match was found.
nikoa64c8c72009-07-20 15:07:26 -0700171bool findMetadata(const Metadata::Filter& filter, const int32_t val)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700172{
173 // Deal with empty and ANY right away
174 if (filter.isEmpty()) return false;
nikoa64c8c72009-07-20 15:07:26 -0700175 if (filter[0] == Metadata::kAny) return true;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700176
Nicolas Catania48290382009-07-10 13:53:06 -0700177 return filter.indexOf(val) >= 0;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700178}
179
180} // anonymous namespace
181
182
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800183namespace android {
184
185// TODO: Temp hack until we can register players
186typedef struct {
187 const char *extension;
188 const player_type playertype;
189} extmap;
190extmap FILE_EXTS [] = {
191 {".mid", SONIVOX_PLAYER},
192 {".midi", SONIVOX_PLAYER},
193 {".smf", SONIVOX_PLAYER},
194 {".xmf", SONIVOX_PLAYER},
195 {".imy", SONIVOX_PLAYER},
196 {".rtttl", SONIVOX_PLAYER},
197 {".rtx", SONIVOX_PLAYER},
198 {".ota", SONIVOX_PLAYER},
Andreas Huberb49676a2010-01-20 16:11:15 -0800199#ifndef NO_OPENCORE
200 {".wma", PV_PLAYER},
201 {".wmv", PV_PLAYER},
202 {".asf", PV_PLAYER},
203#endif
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800204};
205
206// 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 -0800207/* static */ int MediaPlayerService::AudioOutput::mMinBufferCount = 4;
208/* static */ bool MediaPlayerService::AudioOutput::mIsOnEmulator = false;
209
210void MediaPlayerService::instantiate() {
211 defaultServiceManager()->addService(
212 String16("media.player"), new MediaPlayerService());
213}
214
215MediaPlayerService::MediaPlayerService()
216{
217 LOGV("MediaPlayerService created");
218 mNextConnId = 1;
219}
220
221MediaPlayerService::~MediaPlayerService()
222{
223 LOGV("MediaPlayerService destroyed");
224}
225
226sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(pid_t pid)
227{
Gloria Wangdac6a312009-10-29 15:46:37 -0700228 sp<MediaRecorderClient> recorder = new MediaRecorderClient(this, pid);
229 wp<MediaRecorderClient> w = recorder;
230 Mutex::Autolock lock(mLock);
231 mMediaRecorderClients.add(w);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800232 LOGV("Create new media recorder client from pid %d", pid);
233 return recorder;
234}
235
Gloria Wangdac6a312009-10-29 15:46:37 -0700236void MediaPlayerService::removeMediaRecorderClient(wp<MediaRecorderClient> client)
237{
238 Mutex::Autolock lock(mLock);
239 mMediaRecorderClients.remove(client);
240 LOGV("Delete media recorder client");
241}
242
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800243sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever(pid_t pid)
244{
245 sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
246 LOGV("Create new media retriever from pid %d", pid);
247 return retriever;
248}
249
Andreas Huber2db84552010-01-28 11:19:57 -0800250sp<IMediaPlayer> MediaPlayerService::create(
251 pid_t pid, const sp<IMediaPlayerClient>& client, const char* url,
Eric Laurenta514bdb2010-06-21 09:27:30 -0700252 const KeyedVector<String8, String8> *headers, int audioSessionId)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800253{
254 int32_t connId = android_atomic_inc(&mNextConnId);
Eric Laurenta514bdb2010-06-21 09:27:30 -0700255 sp<Client> c = new Client(this, pid, connId, client, audioSessionId);
256 LOGV("Create new client(%d) from pid %d, url=%s, connId=%d, audioSessionId=%d",
257 connId, pid, url, connId, audioSessionId);
Andreas Huber2db84552010-01-28 11:19:57 -0800258 if (NO_ERROR != c->setDataSource(url, headers))
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800259 {
260 c.clear();
261 return c;
262 }
263 wp<Client> w = c;
264 Mutex::Autolock lock(mLock);
265 mClients.add(w);
266 return c;
267}
268
269sp<IMediaPlayer> MediaPlayerService::create(pid_t pid, const sp<IMediaPlayerClient>& client,
Eric Laurenta514bdb2010-06-21 09:27:30 -0700270 int fd, int64_t offset, int64_t length, int audioSessionId)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800271{
272 int32_t connId = android_atomic_inc(&mNextConnId);
Eric Laurenta514bdb2010-06-21 09:27:30 -0700273 sp<Client> c = new Client(this, pid, connId, client, audioSessionId);
274 LOGV("Create new client(%d) from pid %d, fd=%d, offset=%lld, length=%lld, audioSessionId=%d",
275 connId, pid, fd, offset, length, audioSessionId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800276 if (NO_ERROR != c->setDataSource(fd, offset, length)) {
277 c.clear();
278 } else {
279 wp<Client> w = c;
280 Mutex::Autolock lock(mLock);
281 mClients.add(w);
282 }
283 ::close(fd);
284 return c;
285}
286
Andreas Huber318ad9c2009-10-15 13:46:54 -0700287sp<IOMX> MediaPlayerService::getOMX() {
288 Mutex::Autolock autoLock(mLock);
289
290 if (mOMX.get() == NULL) {
291 mOMX = new OMX;
292 }
293
294 return mOMX;
Andreas Huber20111aa2009-07-14 16:56:47 -0700295}
296
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800297status_t MediaPlayerService::AudioCache::dump(int fd, const Vector<String16>& args) const
298{
299 const size_t SIZE = 256;
300 char buffer[SIZE];
301 String8 result;
302
303 result.append(" AudioCache\n");
304 if (mHeap != 0) {
305 snprintf(buffer, 255, " heap base(%p), size(%d), flags(%d), device(%s)\n",
306 mHeap->getBase(), mHeap->getSize(), mHeap->getFlags(), mHeap->getDevice());
307 result.append(buffer);
308 }
309 snprintf(buffer, 255, " msec per frame(%f), channel count(%d), format(%d), frame count(%ld)\n",
310 mMsecsPerFrame, mChannelCount, mFormat, mFrameCount);
311 result.append(buffer);
312 snprintf(buffer, 255, " sample rate(%d), size(%d), error(%d), command complete(%s)\n",
313 mSampleRate, mSize, mError, mCommandComplete?"true":"false");
314 result.append(buffer);
315 ::write(fd, result.string(), result.size());
316 return NO_ERROR;
317}
318
319status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
320{
321 const size_t SIZE = 256;
322 char buffer[SIZE];
323 String8 result;
324
325 result.append(" AudioOutput\n");
326 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n",
327 mStreamType, mLeftVolume, mRightVolume);
328 result.append(buffer);
329 snprintf(buffer, 255, " msec per frame(%f), latency (%d)\n",
330 mMsecsPerFrame, mLatency);
331 result.append(buffer);
332 ::write(fd, result.string(), result.size());
333 if (mTrack != 0) {
334 mTrack->dump(fd, args);
335 }
336 return NO_ERROR;
337}
338
339status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args) const
340{
341 const size_t SIZE = 256;
342 char buffer[SIZE];
343 String8 result;
344 result.append(" Client\n");
345 snprintf(buffer, 255, " pid(%d), connId(%d), status(%d), looping(%s)\n",
346 mPid, mConnId, mStatus, mLoop?"true": "false");
347 result.append(buffer);
348 write(fd, result.string(), result.size());
349 if (mAudioOutput != 0) {
350 mAudioOutput->dump(fd, args);
351 }
352 write(fd, "\n", 1);
353 return NO_ERROR;
354}
355
356static int myTid() {
357#ifdef HAVE_GETTID
358 return gettid();
359#else
360 return getpid();
361#endif
362}
363
364#if defined(__arm__)
365extern "C" void get_malloc_leak_info(uint8_t** info, size_t* overallSize,
366 size_t* infoSize, size_t* totalMemory, size_t* backtraceSize);
367extern "C" void free_malloc_leak_info(uint8_t* info);
368
Andreas Huber1eea7f52009-10-27 15:50:04 -0700369// Use the String-class below instead of String8 to allocate all memory
370// beforehand and not reenter the heap while we are examining it...
371struct MyString8 {
372 static const size_t MAX_SIZE = 256 * 1024;
373
374 MyString8()
375 : mPtr((char *)malloc(MAX_SIZE)) {
376 *mPtr = '\0';
377 }
378
379 ~MyString8() {
380 free(mPtr);
381 }
382
383 void append(const char *s) {
384 strcat(mPtr, s);
385 }
386
387 const char *string() const {
388 return mPtr;
389 }
390
391 size_t size() const {
392 return strlen(mPtr);
393 }
394
395private:
396 char *mPtr;
397
398 MyString8(const MyString8 &);
399 MyString8 &operator=(const MyString8 &);
400};
401
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800402void memStatus(int fd, const Vector<String16>& args)
403{
404 const size_t SIZE = 256;
405 char buffer[SIZE];
Andreas Huber1eea7f52009-10-27 15:50:04 -0700406 MyString8 result;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800407
408 typedef struct {
409 size_t size;
410 size_t dups;
411 intptr_t * backtrace;
412 } AllocEntry;
413
414 uint8_t *info = NULL;
415 size_t overallSize = 0;
416 size_t infoSize = 0;
417 size_t totalMemory = 0;
418 size_t backtraceSize = 0;
419
420 get_malloc_leak_info(&info, &overallSize, &infoSize, &totalMemory, &backtraceSize);
421 if (info) {
422 uint8_t *ptr = info;
423 size_t count = overallSize / infoSize;
424
425 snprintf(buffer, SIZE, " Allocation count %i\n", count);
426 result.append(buffer);
James Dong1edee162010-02-25 10:06:32 -0800427 snprintf(buffer, SIZE, " Total memory %i\n", totalMemory);
428 result.append(buffer);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800429
430 AllocEntry * entries = new AllocEntry[count];
431
432 for (size_t i = 0; i < count; i++) {
433 // Each entry should be size_t, size_t, intptr_t[backtraceSize]
434 AllocEntry *e = &entries[i];
435
436 e->size = *reinterpret_cast<size_t *>(ptr);
437 ptr += sizeof(size_t);
438
439 e->dups = *reinterpret_cast<size_t *>(ptr);
440 ptr += sizeof(size_t);
441
442 e->backtrace = reinterpret_cast<intptr_t *>(ptr);
443 ptr += sizeof(intptr_t) * backtraceSize;
444 }
445
446 // Now we need to sort the entries. They come sorted by size but
447 // not by stack trace which causes problems using diff.
448 bool moved;
449 do {
450 moved = false;
451 for (size_t i = 0; i < (count - 1); i++) {
452 AllocEntry *e1 = &entries[i];
453 AllocEntry *e2 = &entries[i+1];
454
455 bool swap = e1->size < e2->size;
456 if (e1->size == e2->size) {
457 for(size_t j = 0; j < backtraceSize; j++) {
458 if (e1->backtrace[j] == e2->backtrace[j]) {
459 continue;
460 }
461 swap = e1->backtrace[j] < e2->backtrace[j];
462 break;
463 }
464 }
465 if (swap) {
466 AllocEntry t = entries[i];
467 entries[i] = entries[i+1];
468 entries[i+1] = t;
469 moved = true;
470 }
471 }
472 } while (moved);
473
474 for (size_t i = 0; i < count; i++) {
475 AllocEntry *e = &entries[i];
476
James Dong1edee162010-02-25 10:06:32 -0800477 snprintf(buffer, SIZE, "size %8i, dup %4i, ", e->size, e->dups);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800478 result.append(buffer);
479 for (size_t ct = 0; (ct < backtraceSize) && e->backtrace[ct]; ct++) {
480 if (ct) {
481 result.append(", ");
482 }
483 snprintf(buffer, SIZE, "0x%08x", e->backtrace[ct]);
484 result.append(buffer);
485 }
486 result.append("\n");
487 }
488
489 delete[] entries;
490 free_malloc_leak_info(info);
491 }
492
493 write(fd, result.string(), result.size());
494}
495#endif
496
497status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
498{
499 const size_t SIZE = 256;
500 char buffer[SIZE];
501 String8 result;
502 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
503 snprintf(buffer, SIZE, "Permission Denial: "
504 "can't dump MediaPlayerService from pid=%d, uid=%d\n",
505 IPCThreadState::self()->getCallingPid(),
506 IPCThreadState::self()->getCallingUid());
507 result.append(buffer);
508 } else {
509 Mutex::Autolock lock(mLock);
510 for (int i = 0, n = mClients.size(); i < n; ++i) {
511 sp<Client> c = mClients[i].promote();
512 if (c != 0) c->dump(fd, args);
513 }
Gloria Wangdac6a312009-10-29 15:46:37 -0700514 for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
515 result.append(" MediaRecorderClient\n");
516 sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
517 snprintf(buffer, 255, " pid(%d)\n\n", c->mPid);
518 result.append(buffer);
519 }
520
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800521 result.append(" Files opened and/or mapped:\n");
522 snprintf(buffer, SIZE, "/proc/%d/maps", myTid());
523 FILE *f = fopen(buffer, "r");
524 if (f) {
525 while (!feof(f)) {
526 fgets(buffer, SIZE, f);
527 if (strstr(buffer, " /sdcard/") ||
528 strstr(buffer, " /system/sounds/") ||
529 strstr(buffer, " /system/media/")) {
530 result.append(" ");
531 result.append(buffer);
532 }
533 }
534 fclose(f);
535 } else {
536 result.append("couldn't open ");
537 result.append(buffer);
538 result.append("\n");
539 }
540
541 snprintf(buffer, SIZE, "/proc/%d/fd", myTid());
542 DIR *d = opendir(buffer);
543 if (d) {
544 struct dirent *ent;
545 while((ent = readdir(d)) != NULL) {
546 if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
547 snprintf(buffer, SIZE, "/proc/%d/fd/%s", myTid(), ent->d_name);
548 struct stat s;
549 if (lstat(buffer, &s) == 0) {
550 if ((s.st_mode & S_IFMT) == S_IFLNK) {
551 char linkto[256];
552 int len = readlink(buffer, linkto, sizeof(linkto));
553 if(len > 0) {
554 if(len > 255) {
555 linkto[252] = '.';
556 linkto[253] = '.';
557 linkto[254] = '.';
558 linkto[255] = 0;
559 } else {
560 linkto[len] = 0;
561 }
562 if (strstr(linkto, "/sdcard/") == linkto ||
563 strstr(linkto, "/system/sounds/") == linkto ||
564 strstr(linkto, "/system/media/") == linkto) {
565 result.append(" ");
566 result.append(buffer);
567 result.append(" -> ");
568 result.append(linkto);
569 result.append("\n");
570 }
571 }
572 } else {
573 result.append(" unexpected type for ");
574 result.append(buffer);
575 result.append("\n");
576 }
577 }
578 }
579 }
580 closedir(d);
581 } else {
582 result.append("couldn't open ");
583 result.append(buffer);
584 result.append("\n");
585 }
586
587#if defined(__arm__)
588 bool dumpMem = false;
589 for (size_t i = 0; i < args.size(); i++) {
590 if (args[i] == String16("-m")) {
591 dumpMem = true;
592 }
593 }
594 if (dumpMem) {
595 memStatus(fd, args);
596 }
597#endif
598 }
599 write(fd, result.string(), result.size());
600 return NO_ERROR;
601}
602
603void MediaPlayerService::removeClient(wp<Client> client)
604{
605 Mutex::Autolock lock(mLock);
606 mClients.remove(client);
607}
608
609MediaPlayerService::Client::Client(const sp<MediaPlayerService>& service, pid_t pid,
Eric Laurenta514bdb2010-06-21 09:27:30 -0700610 int32_t connId, const sp<IMediaPlayerClient>& client, int audioSessionId)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800611{
612 LOGV("Client(%d) constructor", connId);
613 mPid = pid;
614 mConnId = connId;
615 mService = service;
616 mClient = client;
617 mLoop = false;
618 mStatus = NO_INIT;
Eric Laurenta514bdb2010-06-21 09:27:30 -0700619 mAudioSessionId = audioSessionId;
620
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800621#if CALLBACK_ANTAGONIZER
622 LOGD("create Antagonizer");
623 mAntagonizer = new Antagonizer(notify, this);
624#endif
625}
626
627MediaPlayerService::Client::~Client()
628{
629 LOGV("Client(%d) destructor pid = %d", mConnId, mPid);
630 mAudioOutput.clear();
631 wp<Client> client(this);
632 disconnect();
633 mService->removeClient(client);
634}
635
636void MediaPlayerService::Client::disconnect()
637{
638 LOGV("disconnect(%d) from pid %d", mConnId, mPid);
639 // grab local reference and clear main reference to prevent future
640 // access to object
641 sp<MediaPlayerBase> p;
642 {
643 Mutex::Autolock l(mLock);
644 p = mPlayer;
645 }
Dave Sparks795fa582009-03-24 17:57:12 -0700646 mClient.clear();
Andreas Huber20111aa2009-07-14 16:56:47 -0700647
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800648 mPlayer.clear();
649
650 // clear the notification to prevent callbacks to dead client
651 // and reset the player. We assume the player will serialize
652 // access to itself if necessary.
653 if (p != 0) {
654 p->setNotifyCallback(0, 0);
655#if CALLBACK_ANTAGONIZER
656 LOGD("kill Antagonizer");
657 mAntagonizer->kill();
658#endif
659 p->reset();
660 }
661
662 IPCThreadState::self()->flushCommands();
663}
664
Andreas Huber47f59cf2009-08-07 09:30:32 -0700665static player_type getDefaultPlayerType() {
Andreas Huber608d77b2010-06-23 16:40:57 -0700666 return STAGEFRIGHT_PLAYER;
Andreas Huber47f59cf2009-08-07 09:30:32 -0700667}
668
James Dong148c1a22009-09-06 14:29:45 -0700669player_type getPlayerType(int fd, int64_t offset, int64_t length)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800670{
671 char buf[20];
672 lseek(fd, offset, SEEK_SET);
673 read(fd, buf, sizeof(buf));
674 lseek(fd, offset, SEEK_SET);
675
676 long ident = *((long*)buf);
677
678 // Ogg vorbis?
679 if (ident == 0x5367674f) // 'OggS'
Andreas Huber608d77b2010-06-23 16:40:57 -0700680 return STAGEFRIGHT_PLAYER;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800681
Andreas Huberb49676a2010-01-20 16:11:15 -0800682#ifndef NO_OPENCORE
683 if (ident == 0x75b22630) {
684 // The magic number for .asf files, i.e. wmv and wma content.
685 // These are not currently supported through stagefright.
686 return PV_PLAYER;
687 }
688#endif
689
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800690 // Some kind of MIDI?
691 EAS_DATA_HANDLE easdata;
692 if (EAS_Init(&easdata) == EAS_SUCCESS) {
693 EAS_FILE locator;
694 locator.path = NULL;
695 locator.fd = fd;
696 locator.offset = offset;
697 locator.length = length;
698 EAS_HANDLE eashandle;
699 if (EAS_OpenFile(easdata, &locator, &eashandle) == EAS_SUCCESS) {
700 EAS_CloseFile(easdata, eashandle);
701 EAS_Shutdown(easdata);
702 return SONIVOX_PLAYER;
703 }
704 EAS_Shutdown(easdata);
705 }
706
Andreas Huber47f59cf2009-08-07 09:30:32 -0700707 return getDefaultPlayerType();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800708}
709
James Dong148c1a22009-09-06 14:29:45 -0700710player_type getPlayerType(const char* url)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800711{
Nicolas Catania14d27472009-07-13 14:37:49 -0700712 if (TestPlayerStub::canBeUsed(url)) {
713 return TEST_PLAYER;
714 }
715
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800716 // use MidiFile for MIDI extensions
717 int lenURL = strlen(url);
718 for (int i = 0; i < NELEM(FILE_EXTS); ++i) {
719 int len = strlen(FILE_EXTS[i].extension);
720 int start = lenURL - len;
721 if (start > 0) {
Atsushi Enofc1c7b92010-03-19 23:18:02 +0900722 if (!strncasecmp(url + start, FILE_EXTS[i].extension, len)) {
Andreas Huber608d77b2010-06-23 16:40:57 -0700723 return FILE_EXTS[i].playertype;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800724 }
725 }
726 }
727
James Dong27fde952010-04-13 21:33:26 -0700728 if (!strncasecmp(url, "rtsp://", 7)) {
Andreas Hubercf7b9c72010-06-07 15:19:40 -0700729 char value[PROPERTY_VALUE_MAX];
730 if (!property_get("media.stagefright.enable-rtsp", value, NULL)
731 || (strcmp(value, "1") && strcasecmp(value, "true"))) {
732 // For now, we're going to use PV for rtsp-based playback
733 // by default until we can clear up a few more issues.
734 return PV_PLAYER;
735 }
James Dong27fde952010-04-13 21:33:26 -0700736 }
737
Andreas Huber47f59cf2009-08-07 09:30:32 -0700738 return getDefaultPlayerType();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800739}
740
741static sp<MediaPlayerBase> createPlayer(player_type playerType, void* cookie,
742 notify_callback_f notifyFunc)
743{
744 sp<MediaPlayerBase> p;
745 switch (playerType) {
Jean-Baptiste Queru6c5b2102009-03-21 11:40:18 -0700746#ifndef NO_OPENCORE
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800747 case PV_PLAYER:
748 LOGV(" create PVPlayer");
749 p = new PVPlayer();
750 break;
Jean-Baptiste Queru6c5b2102009-03-21 11:40:18 -0700751#endif
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800752 case SONIVOX_PLAYER:
753 LOGV(" create MidiFile");
754 p = new MidiFile();
755 break;
Andreas Huber20111aa2009-07-14 16:56:47 -0700756 case STAGEFRIGHT_PLAYER:
757 LOGV(" create StagefrightPlayer");
758 p = new StagefrightPlayer;
759 break;
Nicolas Catania14d27472009-07-13 14:37:49 -0700760 case TEST_PLAYER:
761 LOGV("Create Test Player stub");
762 p = new TestPlayerStub();
763 break;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800764 }
765 if (p != NULL) {
766 if (p->initCheck() == NO_ERROR) {
767 p->setNotifyCallback(cookie, notifyFunc);
768 } else {
769 p.clear();
770 }
771 }
772 if (p == NULL) {
773 LOGE("Failed to create player object");
774 }
775 return p;
776}
777
778sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
779{
780 // determine if we have the right player type
781 sp<MediaPlayerBase> p = mPlayer;
782 if ((p != NULL) && (p->playerType() != playerType)) {
783 LOGV("delete player");
784 p.clear();
785 }
786 if (p == NULL) {
787 p = android::createPlayer(playerType, this, notify);
788 }
789 return p;
790}
791
Andreas Huber2db84552010-01-28 11:19:57 -0800792status_t MediaPlayerService::Client::setDataSource(
793 const char *url, const KeyedVector<String8, String8> *headers)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800794{
795 LOGV("setDataSource(%s)", url);
796 if (url == NULL)
797 return UNKNOWN_ERROR;
798
799 if (strncmp(url, "content://", 10) == 0) {
800 // get a filedescriptor for the content Uri and
801 // pass it to the setDataSource(fd) method
802
803 String16 url16(url);
804 int fd = android::openContentProviderFile(url16);
805 if (fd < 0)
806 {
807 LOGE("Couldn't open fd for %s", url);
808 return UNKNOWN_ERROR;
809 }
810 setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
811 close(fd);
812 return mStatus;
813 } else {
814 player_type playerType = getPlayerType(url);
815 LOGV("player type = %d", playerType);
816
817 // create the right type of player
818 sp<MediaPlayerBase> p = createPlayer(playerType);
819 if (p == NULL) return NO_INIT;
820
821 if (!p->hardwareOutput()) {
Eric Laurenta514bdb2010-06-21 09:27:30 -0700822 mAudioOutput = new AudioOutput(mAudioSessionId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800823 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
824 }
825
826 // now set data source
827 LOGV(" setDataSource");
Andreas Huber2db84552010-01-28 11:19:57 -0800828 mStatus = p->setDataSource(url, headers);
Nicolas Catania14d27472009-07-13 14:37:49 -0700829 if (mStatus == NO_ERROR) {
830 mPlayer = p;
831 } else {
832 LOGE(" error: %d", mStatus);
833 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800834 return mStatus;
835 }
836}
837
838status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
839{
840 LOGV("setDataSource fd=%d, offset=%lld, length=%lld", fd, offset, length);
841 struct stat sb;
842 int ret = fstat(fd, &sb);
843 if (ret != 0) {
844 LOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
845 return UNKNOWN_ERROR;
846 }
847
848 LOGV("st_dev = %llu", sb.st_dev);
849 LOGV("st_mode = %u", sb.st_mode);
850 LOGV("st_uid = %lu", sb.st_uid);
851 LOGV("st_gid = %lu", sb.st_gid);
852 LOGV("st_size = %llu", sb.st_size);
853
854 if (offset >= sb.st_size) {
855 LOGE("offset error");
856 ::close(fd);
857 return UNKNOWN_ERROR;
858 }
859 if (offset + length > sb.st_size) {
860 length = sb.st_size - offset;
861 LOGV("calculated length = %lld", length);
862 }
863
864 player_type playerType = getPlayerType(fd, offset, length);
865 LOGV("player type = %d", playerType);
866
867 // create the right type of player
868 sp<MediaPlayerBase> p = createPlayer(playerType);
869 if (p == NULL) return NO_INIT;
870
871 if (!p->hardwareOutput()) {
Eric Laurenta514bdb2010-06-21 09:27:30 -0700872 mAudioOutput = new AudioOutput(mAudioSessionId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800873 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
874 }
875
876 // now set data source
877 mStatus = p->setDataSource(fd, offset, length);
878 if (mStatus == NO_ERROR) mPlayer = p;
879 return mStatus;
880}
881
882status_t MediaPlayerService::Client::setVideoSurface(const sp<ISurface>& surface)
883{
884 LOGV("[%d] setVideoSurface(%p)", mConnId, surface.get());
885 sp<MediaPlayerBase> p = getPlayer();
886 if (p == 0) return UNKNOWN_ERROR;
887 return p->setVideoSurface(surface);
888}
889
Nicolas Catania1d187f12009-05-12 23:25:55 -0700890status_t MediaPlayerService::Client::invoke(const Parcel& request,
891 Parcel *reply)
892{
893 sp<MediaPlayerBase> p = getPlayer();
894 if (p == NULL) return UNKNOWN_ERROR;
895 return p->invoke(request, reply);
896}
897
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700898// This call doesn't need to access the native player.
899status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
900{
901 status_t status;
nikoa64c8c72009-07-20 15:07:26 -0700902 media::Metadata::Filter allow, drop;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700903
Nicolas Catania48290382009-07-10 13:53:06 -0700904 if (unmarshallFilter(filter, &allow, &status) &&
905 unmarshallFilter(filter, &drop, &status)) {
906 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700907
908 mMetadataAllow = allow;
909 mMetadataDrop = drop;
910 }
911 return status;
912}
913
Nicolas Catania48290382009-07-10 13:53:06 -0700914status_t MediaPlayerService::Client::getMetadata(
915 bool update_only, bool apply_filter, Parcel *reply)
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700916{
nikoa64c8c72009-07-20 15:07:26 -0700917 sp<MediaPlayerBase> player = getPlayer();
918 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania48290382009-07-10 13:53:06 -0700919
nikod608a812009-07-16 16:39:53 -0700920 status_t status;
921 // Placeholder for the return code, updated by the caller.
922 reply->writeInt32(-1);
923
nikoa64c8c72009-07-20 15:07:26 -0700924 media::Metadata::Filter ids;
Nicolas Catania48290382009-07-10 13:53:06 -0700925
926 // We don't block notifications while we fetch the data. We clear
927 // mMetadataUpdated first so we don't lose notifications happening
928 // during the rest of this call.
929 {
930 Mutex::Autolock lock(mLock);
931 if (update_only) {
nikod608a812009-07-16 16:39:53 -0700932 ids = mMetadataUpdated;
Nicolas Catania48290382009-07-10 13:53:06 -0700933 }
934 mMetadataUpdated.clear();
935 }
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700936
nikoa64c8c72009-07-20 15:07:26 -0700937 media::Metadata metadata(reply);
Nicolas Catania48290382009-07-10 13:53:06 -0700938
nikoa64c8c72009-07-20 15:07:26 -0700939 metadata.appendHeader();
940 status = player->getMetadata(ids, reply);
nikod608a812009-07-16 16:39:53 -0700941
942 if (status != OK) {
nikoa64c8c72009-07-20 15:07:26 -0700943 metadata.resetParcel();
nikod608a812009-07-16 16:39:53 -0700944 LOGE("getMetadata failed %d", status);
945 return status;
946 }
947
948 // FIXME: Implement filtering on the result. Not critical since
949 // filtering takes place on the update notifications already. This
950 // would be when all the metadata are fetch and a filter is set.
951
nikod608a812009-07-16 16:39:53 -0700952 // Everything is fine, update the metadata length.
nikoa64c8c72009-07-20 15:07:26 -0700953 metadata.updateLength();
nikod608a812009-07-16 16:39:53 -0700954 return OK;
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700955}
956
Andreas Huber4e92c7e2010-02-12 12:35:58 -0800957status_t MediaPlayerService::Client::suspend() {
958 sp<MediaPlayerBase> p = getPlayer();
959 if (p == 0) return UNKNOWN_ERROR;
960
961 return p->suspend();
962}
963
964status_t MediaPlayerService::Client::resume() {
965 sp<MediaPlayerBase> p = getPlayer();
966 if (p == 0) return UNKNOWN_ERROR;
967
968 return p->resume();
969}
970
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800971status_t MediaPlayerService::Client::prepareAsync()
972{
973 LOGV("[%d] prepareAsync", mConnId);
974 sp<MediaPlayerBase> p = getPlayer();
975 if (p == 0) return UNKNOWN_ERROR;
976 status_t ret = p->prepareAsync();
977#if CALLBACK_ANTAGONIZER
978 LOGD("start Antagonizer");
979 if (ret == NO_ERROR) mAntagonizer->start();
980#endif
981 return ret;
982}
983
984status_t MediaPlayerService::Client::start()
985{
986 LOGV("[%d] start", mConnId);
987 sp<MediaPlayerBase> p = getPlayer();
988 if (p == 0) return UNKNOWN_ERROR;
989 p->setLooping(mLoop);
990 return p->start();
991}
992
993status_t MediaPlayerService::Client::stop()
994{
995 LOGV("[%d] stop", mConnId);
996 sp<MediaPlayerBase> p = getPlayer();
997 if (p == 0) return UNKNOWN_ERROR;
998 return p->stop();
999}
1000
1001status_t MediaPlayerService::Client::pause()
1002{
1003 LOGV("[%d] pause", mConnId);
1004 sp<MediaPlayerBase> p = getPlayer();
1005 if (p == 0) return UNKNOWN_ERROR;
1006 return p->pause();
1007}
1008
1009status_t MediaPlayerService::Client::isPlaying(bool* state)
1010{
1011 *state = false;
1012 sp<MediaPlayerBase> p = getPlayer();
1013 if (p == 0) return UNKNOWN_ERROR;
1014 *state = p->isPlaying();
1015 LOGV("[%d] isPlaying: %d", mConnId, *state);
1016 return NO_ERROR;
1017}
1018
1019status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
1020{
1021 LOGV("getCurrentPosition");
1022 sp<MediaPlayerBase> p = getPlayer();
1023 if (p == 0) return UNKNOWN_ERROR;
1024 status_t ret = p->getCurrentPosition(msec);
1025 if (ret == NO_ERROR) {
1026 LOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
1027 } else {
1028 LOGE("getCurrentPosition returned %d", ret);
1029 }
1030 return ret;
1031}
1032
1033status_t MediaPlayerService::Client::getDuration(int *msec)
1034{
1035 LOGV("getDuration");
1036 sp<MediaPlayerBase> p = getPlayer();
1037 if (p == 0) return UNKNOWN_ERROR;
1038 status_t ret = p->getDuration(msec);
1039 if (ret == NO_ERROR) {
1040 LOGV("[%d] getDuration = %d", mConnId, *msec);
1041 } else {
1042 LOGE("getDuration returned %d", ret);
1043 }
1044 return ret;
1045}
1046
1047status_t MediaPlayerService::Client::seekTo(int msec)
1048{
1049 LOGV("[%d] seekTo(%d)", mConnId, msec);
1050 sp<MediaPlayerBase> p = getPlayer();
1051 if (p == 0) return UNKNOWN_ERROR;
1052 return p->seekTo(msec);
1053}
1054
1055status_t MediaPlayerService::Client::reset()
1056{
1057 LOGV("[%d] reset", mConnId);
1058 sp<MediaPlayerBase> p = getPlayer();
1059 if (p == 0) return UNKNOWN_ERROR;
1060 return p->reset();
1061}
1062
1063status_t MediaPlayerService::Client::setAudioStreamType(int type)
1064{
1065 LOGV("[%d] setAudioStreamType(%d)", mConnId, type);
1066 // TODO: for hardware output, call player instead
1067 Mutex::Autolock l(mLock);
1068 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1069 return NO_ERROR;
1070}
1071
1072status_t MediaPlayerService::Client::setLooping(int loop)
1073{
1074 LOGV("[%d] setLooping(%d)", mConnId, loop);
1075 mLoop = loop;
1076 sp<MediaPlayerBase> p = getPlayer();
1077 if (p != 0) return p->setLooping(loop);
1078 return NO_ERROR;
1079}
1080
1081status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1082{
1083 LOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
1084 // TODO: for hardware output, call player instead
1085 Mutex::Autolock l(mLock);
1086 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1087 return NO_ERROR;
1088}
1089
Nicolas Catania48290382009-07-10 13:53:06 -07001090
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001091void MediaPlayerService::Client::notify(void* cookie, int msg, int ext1, int ext2)
1092{
1093 Client* client = static_cast<Client*>(cookie);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001094
1095 if (MEDIA_INFO == msg &&
Nicolas Catania48290382009-07-10 13:53:06 -07001096 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikoa64c8c72009-07-20 15:07:26 -07001097 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania48290382009-07-10 13:53:06 -07001098
1099 if(client->shouldDropMetadata(metadata_type)) {
1100 return;
1101 }
1102
1103 // Update the list of metadata that have changed. getMetadata
1104 // also access mMetadataUpdated and clears it.
1105 client->addNewMetadataUpdate(metadata_type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001106 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001107 LOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
1108 client->mClient->notify(msg, ext1, ext2);
1109}
1110
Nicolas Catania48290382009-07-10 13:53:06 -07001111
nikoa64c8c72009-07-20 15:07:26 -07001112bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001113{
Nicolas Catania48290382009-07-10 13:53:06 -07001114 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001115
Nicolas Catania48290382009-07-10 13:53:06 -07001116 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001117 return true;
1118 }
1119
Nicolas Catania48290382009-07-10 13:53:06 -07001120 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001121 return false;
Nicolas Catania48290382009-07-10 13:53:06 -07001122 } else {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001123 return true;
1124 }
1125}
1126
Nicolas Catania48290382009-07-10 13:53:06 -07001127
nikoa64c8c72009-07-20 15:07:26 -07001128void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania48290382009-07-10 13:53:06 -07001129 Mutex::Autolock lock(mLock);
1130 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1131 mMetadataUpdated.add(metadata_type);
1132 }
1133}
1134
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001135#if CALLBACK_ANTAGONIZER
1136const int Antagonizer::interval = 10000; // 10 msecs
1137
1138Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1139 mExit(false), mActive(false), mClient(client), mCb(cb)
1140{
1141 createThread(callbackThread, this);
1142}
1143
1144void Antagonizer::kill()
1145{
1146 Mutex::Autolock _l(mLock);
1147 mActive = false;
1148 mExit = true;
1149 mCondition.wait(mLock);
1150}
1151
1152int Antagonizer::callbackThread(void* user)
1153{
1154 LOGD("Antagonizer started");
1155 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1156 while (!p->mExit) {
1157 if (p->mActive) {
1158 LOGV("send event");
1159 p->mCb(p->mClient, 0, 0, 0);
1160 }
1161 usleep(interval);
1162 }
1163 Mutex::Autolock _l(p->mLock);
1164 p->mCondition.signal();
1165 LOGD("Antagonizer stopped");
1166 return 0;
1167}
1168#endif
1169
1170static size_t kDefaultHeapSize = 1024 * 1024; // 1MB
1171
1172sp<IMemory> MediaPlayerService::decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1173{
1174 LOGV("decode(%s)", url);
1175 sp<MemoryBase> mem;
1176 sp<MediaPlayerBase> player;
1177
1178 // Protect our precious, precious DRMd ringtones by only allowing
1179 // decoding of http, but not filesystem paths or content Uris.
1180 // If the application wants to decode those, it should open a
1181 // filedescriptor for them and use that.
1182 if (url != NULL && strncmp(url, "http://", 7) != 0) {
1183 LOGD("Can't decode %s by path, use filedescriptor instead", url);
1184 return mem;
1185 }
1186
1187 player_type playerType = getPlayerType(url);
1188 LOGV("player type = %d", playerType);
1189
1190 // create the right type of player
1191 sp<AudioCache> cache = new AudioCache(url);
1192 player = android::createPlayer(playerType, cache.get(), cache->notify);
1193 if (player == NULL) goto Exit;
1194 if (player->hardwareOutput()) goto Exit;
1195
1196 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1197
1198 // set data source
1199 if (player->setDataSource(url) != NO_ERROR) goto Exit;
1200
1201 LOGV("prepare");
1202 player->prepareAsync();
1203
1204 LOGV("wait for prepare");
1205 if (cache->wait() != NO_ERROR) goto Exit;
1206
1207 LOGV("start");
1208 player->start();
1209
1210 LOGV("wait for playback complete");
1211 if (cache->wait() != NO_ERROR) goto Exit;
1212
1213 mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1214 *pSampleRate = cache->sampleRate();
1215 *pNumChannels = cache->channelCount();
1216 *pFormat = cache->format();
1217 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1218
1219Exit:
1220 if (player != 0) player->reset();
1221 return mem;
1222}
1223
1224sp<IMemory> MediaPlayerService::decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1225{
1226 LOGV("decode(%d, %lld, %lld)", fd, offset, length);
1227 sp<MemoryBase> mem;
1228 sp<MediaPlayerBase> player;
1229
1230 player_type playerType = getPlayerType(fd, offset, length);
1231 LOGV("player type = %d", playerType);
1232
1233 // create the right type of player
1234 sp<AudioCache> cache = new AudioCache("decode_fd");
1235 player = android::createPlayer(playerType, cache.get(), cache->notify);
1236 if (player == NULL) goto Exit;
1237 if (player->hardwareOutput()) goto Exit;
1238
1239 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1240
1241 // set data source
1242 if (player->setDataSource(fd, offset, length) != NO_ERROR) goto Exit;
1243
1244 LOGV("prepare");
1245 player->prepareAsync();
1246
1247 LOGV("wait for prepare");
1248 if (cache->wait() != NO_ERROR) goto Exit;
1249
1250 LOGV("start");
1251 player->start();
1252
1253 LOGV("wait for playback complete");
1254 if (cache->wait() != NO_ERROR) goto Exit;
1255
1256 mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1257 *pSampleRate = cache->sampleRate();
1258 *pNumChannels = cache->channelCount();
1259 *pFormat = cache->format();
1260 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1261
1262Exit:
1263 if (player != 0) player->reset();
1264 ::close(fd);
1265 return mem;
1266}
1267
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001268/*
1269 * Avert your eyes, ugly hack ahead.
1270 * The following is to support music visualizations.
1271 */
1272
1273static const int NUMVIZBUF = 32;
1274static const int VIZBUFFRAMES = 1024;
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08001275static const int BUFTIMEMSEC = NUMVIZBUF * VIZBUFFRAMES * 1000 / 44100;
1276static const int TOTALBUFTIMEMSEC = NUMVIZBUF * BUFTIMEMSEC;
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001277
1278static bool gotMem = false;
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08001279static sp<MemoryHeapBase> heap;
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001280static sp<MemoryBase> mem[NUMVIZBUF];
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08001281static uint64_t endTime;
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001282static uint64_t lastReadTime;
1283static uint64_t lastWriteTime;
1284static int writeIdx = 0;
1285
1286static void allocVizBufs() {
1287 if (!gotMem) {
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08001288 heap = new MemoryHeapBase(NUMVIZBUF * VIZBUFFRAMES * 2, 0, "snooper");
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001289 for (int i=0;i<NUMVIZBUF;i++) {
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08001290 mem[i] = new MemoryBase(heap, VIZBUFFRAMES * 2 * i, VIZBUFFRAMES * 2);
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001291 }
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08001292 endTime = 0;
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001293 gotMem = true;
1294 }
1295}
1296
1297
1298/*
1299 * Get a buffer of audio data that is about to be played.
1300 * We don't synchronize this because in practice the writer
1301 * is ahead of the reader, and even if we did happen to catch
1302 * a buffer while it's being written, it's just a visualization,
1303 * so no harm done.
1304 */
1305static sp<MemoryBase> getVizBuffer() {
1306
1307 allocVizBufs();
1308
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08001309 lastReadTime = uptimeMillis();
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001310
1311 // if there is no recent buffer (yet), just return empty handed
1312 if (lastWriteTime + TOTALBUFTIMEMSEC < lastReadTime) {
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08001313 //LOGI("@@@@ no audio data to look at yet: %d + %d < %d", (int)lastWriteTime, TOTALBUFTIMEMSEC, (int)lastReadTime);
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001314 return NULL;
1315 }
1316
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08001317 int timedelta = endTime - lastReadTime;
1318 if (timedelta < 0) timedelta = 0;
1319 int framedelta = timedelta * 44100 / 1000;
1320 int headIdx = (writeIdx - framedelta) / VIZBUFFRAMES - 1;
1321 while (headIdx < 0) {
1322 headIdx += NUMVIZBUF;
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001323 }
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08001324 return mem[headIdx];
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001325}
1326
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08001327// Append the data to the vizualization buffer
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001328static void makeVizBuffers(const char *data, int len, uint64_t time) {
1329
1330 allocVizBufs();
1331
1332 uint64_t startTime = time;
1333 const int frameSize = 4; // 16 bit stereo sample is 4 bytes
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08001334 int offset = writeIdx;
1335 int maxoff = heap->getSize() / 2; // in shorts
1336 short *base = (short*)heap->getBase();
1337 short *src = (short*)data;
1338 while (len > 0) {
1339
1340 // Degrade quality by mixing to mono and clearing the lowest 3 bits.
1341 // This should still be good enough for a visualization
1342 base[offset++] = ((int(src[0]) + int(src[1])) >> 1) & ~0x7;
1343 src += 2;
1344 len -= frameSize;
1345 if (offset >= maxoff) {
1346 offset = 0;
1347 }
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001348 }
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08001349 writeIdx = offset;
1350 endTime = time + (len / frameSize) / 44;
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001351 //LOGI("@@@ stored buffers from %d to %d", uint32_t(startTime), uint32_t(time));
1352}
1353
1354sp<IMemory> MediaPlayerService::snoop()
1355{
1356 sp<MemoryBase> mem = getVizBuffer();
1357 return mem;
1358}
1359
1360
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001361#undef LOG_TAG
1362#define LOG_TAG "AudioSink"
Eric Laurenta514bdb2010-06-21 09:27:30 -07001363MediaPlayerService::AudioOutput::AudioOutput(int sessionId)
Andreas Huber20111aa2009-07-14 16:56:47 -07001364 : mCallback(NULL),
Eric Laurenta514bdb2010-06-21 09:27:30 -07001365 mCallbackCookie(NULL),
1366 mSessionId(sessionId) {
1367 LOGV("AudioOutput(%d)", sessionId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001368 mTrack = 0;
1369 mStreamType = AudioSystem::MUSIC;
1370 mLeftVolume = 1.0;
1371 mRightVolume = 1.0;
1372 mLatency = 0;
1373 mMsecsPerFrame = 0;
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001374 mNumFramesWritten = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001375 setMinBufferCount();
1376}
1377
1378MediaPlayerService::AudioOutput::~AudioOutput()
1379{
1380 close();
1381}
1382
1383void MediaPlayerService::AudioOutput::setMinBufferCount()
1384{
1385 char value[PROPERTY_VALUE_MAX];
1386 if (property_get("ro.kernel.qemu", value, 0)) {
1387 mIsOnEmulator = true;
1388 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1389 }
1390}
1391
1392bool MediaPlayerService::AudioOutput::isOnEmulator()
1393{
1394 setMinBufferCount();
1395 return mIsOnEmulator;
1396}
1397
1398int MediaPlayerService::AudioOutput::getMinBufferCount()
1399{
1400 setMinBufferCount();
1401 return mMinBufferCount;
1402}
1403
1404ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1405{
1406 if (mTrack == 0) return NO_INIT;
1407 return mTrack->frameCount() * frameSize();
1408}
1409
1410ssize_t MediaPlayerService::AudioOutput::frameCount() const
1411{
1412 if (mTrack == 0) return NO_INIT;
1413 return mTrack->frameCount();
1414}
1415
1416ssize_t MediaPlayerService::AudioOutput::channelCount() const
1417{
1418 if (mTrack == 0) return NO_INIT;
1419 return mTrack->channelCount();
1420}
1421
1422ssize_t MediaPlayerService::AudioOutput::frameSize() const
1423{
1424 if (mTrack == 0) return NO_INIT;
1425 return mTrack->frameSize();
1426}
1427
1428uint32_t MediaPlayerService::AudioOutput::latency () const
1429{
1430 return mLatency;
1431}
1432
1433float MediaPlayerService::AudioOutput::msecsPerFrame() const
1434{
1435 return mMsecsPerFrame;
1436}
1437
Eric Laurent342e9cf2010-01-19 17:37:09 -08001438status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position)
1439{
1440 if (mTrack == 0) return NO_INIT;
1441 return mTrack->getPosition(position);
1442}
1443
Andreas Huber20111aa2009-07-14 16:56:47 -07001444status_t MediaPlayerService::AudioOutput::open(
1445 uint32_t sampleRate, int channelCount, int format, int bufferCount,
1446 AudioCallback cb, void *cookie)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001447{
Andreas Huber20111aa2009-07-14 16:56:47 -07001448 mCallback = cb;
1449 mCallbackCookie = cookie;
1450
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001451 // Check argument "bufferCount" against the mininum buffer count
1452 if (bufferCount < mMinBufferCount) {
1453 LOGD("bufferCount (%d) is too small and increased to %d", bufferCount, mMinBufferCount);
1454 bufferCount = mMinBufferCount;
1455
1456 }
Eric Laurenta514bdb2010-06-21 09:27:30 -07001457 LOGV("open(%u, %d, %d, %d, %d)", sampleRate, channelCount, format, bufferCount,mSessionId);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001458 if (mTrack) close();
1459 int afSampleRate;
1460 int afFrameCount;
1461 int frameCount;
1462
1463 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1464 return NO_INIT;
1465 }
1466 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1467 return NO_INIT;
1468 }
1469
1470 frameCount = (sampleRate*afFrameCount*bufferCount)/afSampleRate;
Andreas Huber20111aa2009-07-14 16:56:47 -07001471
1472 AudioTrack *t;
1473 if (mCallback != NULL) {
1474 t = new AudioTrack(
Eric Laurentc2f1f072009-07-17 12:17:14 -07001475 mStreamType,
1476 sampleRate,
1477 format,
1478 (channelCount == 2) ? AudioSystem::CHANNEL_OUT_STEREO : AudioSystem::CHANNEL_OUT_MONO,
1479 frameCount,
1480 0 /* flags */,
1481 CallbackWrapper,
Eric Laurenta514bdb2010-06-21 09:27:30 -07001482 this,
1483 0,
1484 mSessionId);
Andreas Huber20111aa2009-07-14 16:56:47 -07001485 } else {
1486 t = new AudioTrack(
Eric Laurentc2f1f072009-07-17 12:17:14 -07001487 mStreamType,
1488 sampleRate,
1489 format,
1490 (channelCount == 2) ? AudioSystem::CHANNEL_OUT_STEREO : AudioSystem::CHANNEL_OUT_MONO,
Eric Laurenta514bdb2010-06-21 09:27:30 -07001491 frameCount,
1492 0,
1493 NULL,
1494 NULL,
1495 0,
1496 mSessionId);
Andreas Huber20111aa2009-07-14 16:56:47 -07001497 }
1498
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001499 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1500 LOGE("Unable to create audio track");
1501 delete t;
1502 return NO_INIT;
1503 }
1504
1505 LOGV("setVolume");
1506 t->setVolume(mLeftVolume, mRightVolume);
1507 mMsecsPerFrame = 1.e3 / (float) sampleRate;
Dave Sparks1d711f62009-12-03 10:13:32 -08001508 mLatency = t->latency();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001509 mTrack = t;
1510 return NO_ERROR;
1511}
1512
1513void MediaPlayerService::AudioOutput::start()
1514{
1515 LOGV("start");
1516 if (mTrack) {
1517 mTrack->setVolume(mLeftVolume, mRightVolume);
1518 mTrack->start();
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001519 mTrack->getPosition(&mNumFramesWritten);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001520 }
1521}
1522
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08001523void MediaPlayerService::AudioOutput::snoopWrite(const void* buffer, size_t size) {
1524 // Only make visualization buffers if anyone recently requested visualization data
1525 uint64_t now = uptimeMillis();
1526 if (lastReadTime + TOTALBUFTIMEMSEC >= now) {
1527 // Based on the current play counter, the number of frames written and
1528 // the current real time we can calculate the approximate real start
1529 // time of the buffer we're about to write.
1530 uint32_t pos;
1531 mTrack->getPosition(&pos);
1532
1533 // we're writing ahead by this many frames:
1534 int ahead = mNumFramesWritten - pos;
1535 //LOGI("@@@ written: %d, playpos: %d, latency: %d", mNumFramesWritten, pos, mTrack->latency());
1536 // which is this many milliseconds, assuming 44100 Hz:
1537 ahead /= 44;
1538
1539 makeVizBuffers((const char*)buffer, size, now + ahead + mTrack->latency());
1540 lastWriteTime = now;
1541 }
1542}
1543
1544
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001545ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size)
1546{
Andreas Huber20111aa2009-07-14 16:56:47 -07001547 LOG_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
1548
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001549 //LOGV("write(%p, %u)", buffer, size);
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001550 if (mTrack) {
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08001551 snoopWrite(buffer, size);
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001552 ssize_t ret = mTrack->write(buffer, size);
1553 mNumFramesWritten += ret / 4; // assume 16 bit stereo
1554 return ret;
1555 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001556 return NO_INIT;
1557}
1558
1559void MediaPlayerService::AudioOutput::stop()
1560{
1561 LOGV("stop");
1562 if (mTrack) mTrack->stop();
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001563 lastWriteTime = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001564}
1565
1566void MediaPlayerService::AudioOutput::flush()
1567{
1568 LOGV("flush");
1569 if (mTrack) mTrack->flush();
1570}
1571
1572void MediaPlayerService::AudioOutput::pause()
1573{
1574 LOGV("pause");
1575 if (mTrack) mTrack->pause();
Marco Nelissen6741eb82009-11-02 13:52:11 -08001576 lastWriteTime = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001577}
1578
1579void MediaPlayerService::AudioOutput::close()
1580{
1581 LOGV("close");
1582 delete mTrack;
1583 mTrack = 0;
1584}
1585
1586void MediaPlayerService::AudioOutput::setVolume(float left, float right)
1587{
1588 LOGV("setVolume(%f, %f)", left, right);
1589 mLeftVolume = left;
1590 mRightVolume = right;
1591 if (mTrack) {
1592 mTrack->setVolume(left, right);
1593 }
1594}
1595
Andreas Huber20111aa2009-07-14 16:56:47 -07001596// static
1597void MediaPlayerService::AudioOutput::CallbackWrapper(
1598 int event, void *cookie, void *info) {
Marco Nelissen7ee8ac92010-01-12 09:23:54 -08001599 //LOGV("callbackwrapper");
Andreas Huber20111aa2009-07-14 16:56:47 -07001600 if (event != AudioTrack::EVENT_MORE_DATA) {
1601 return;
1602 }
1603
1604 AudioOutput *me = (AudioOutput *)cookie;
1605 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
1606
Andreas Huber7d5b8a72010-02-09 16:59:18 -08001607 size_t actualSize = (*me->mCallback)(
Andreas Huber20111aa2009-07-14 16:56:47 -07001608 me, buffer->raw, buffer->size, me->mCallbackCookie);
Andreas Huber7d5b8a72010-02-09 16:59:18 -08001609
Andreas Huber2e8ffaf2010-02-18 16:45:13 -08001610 buffer->size = actualSize;
1611
Andreas Huber7d5b8a72010-02-09 16:59:18 -08001612 if (actualSize > 0) {
1613 me->snoopWrite(buffer->raw, actualSize);
1614 }
Andreas Huber20111aa2009-07-14 16:56:47 -07001615}
1616
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001617#undef LOG_TAG
1618#define LOG_TAG "AudioCache"
1619MediaPlayerService::AudioCache::AudioCache(const char* name) :
1620 mChannelCount(0), mFrameCount(1024), mSampleRate(0), mSize(0),
1621 mError(NO_ERROR), mCommandComplete(false)
1622{
1623 // create ashmem heap
1624 mHeap = new MemoryHeapBase(kDefaultHeapSize, 0, name);
1625}
1626
1627uint32_t MediaPlayerService::AudioCache::latency () const
1628{
1629 return 0;
1630}
1631
1632float MediaPlayerService::AudioCache::msecsPerFrame() const
1633{
1634 return mMsecsPerFrame;
1635}
1636
Eric Laurent342e9cf2010-01-19 17:37:09 -08001637status_t MediaPlayerService::AudioCache::getPosition(uint32_t *position)
1638{
1639 if (position == 0) return BAD_VALUE;
1640 *position = mSize;
1641 return NO_ERROR;
1642}
1643
Andreas Huber7d5b8a72010-02-09 16:59:18 -08001644////////////////////////////////////////////////////////////////////////////////
1645
1646struct CallbackThread : public Thread {
1647 CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
1648 MediaPlayerBase::AudioSink::AudioCallback cb,
1649 void *cookie);
1650
1651protected:
1652 virtual ~CallbackThread();
1653
1654 virtual bool threadLoop();
1655
1656private:
1657 wp<MediaPlayerBase::AudioSink> mSink;
1658 MediaPlayerBase::AudioSink::AudioCallback mCallback;
1659 void *mCookie;
1660 void *mBuffer;
1661 size_t mBufferSize;
1662
1663 CallbackThread(const CallbackThread &);
1664 CallbackThread &operator=(const CallbackThread &);
1665};
1666
1667CallbackThread::CallbackThread(
1668 const wp<MediaPlayerBase::AudioSink> &sink,
1669 MediaPlayerBase::AudioSink::AudioCallback cb,
1670 void *cookie)
1671 : mSink(sink),
1672 mCallback(cb),
1673 mCookie(cookie),
1674 mBuffer(NULL),
1675 mBufferSize(0) {
1676}
1677
1678CallbackThread::~CallbackThread() {
1679 if (mBuffer) {
1680 free(mBuffer);
1681 mBuffer = NULL;
1682 }
1683}
1684
1685bool CallbackThread::threadLoop() {
1686 sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
1687 if (sink == NULL) {
1688 return false;
1689 }
1690
1691 if (mBuffer == NULL) {
1692 mBufferSize = sink->bufferSize();
1693 mBuffer = malloc(mBufferSize);
1694 }
1695
1696 size_t actualSize =
1697 (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie);
1698
1699 if (actualSize > 0) {
1700 sink->write(mBuffer, actualSize);
1701 }
1702
1703 return true;
1704}
1705
1706////////////////////////////////////////////////////////////////////////////////
1707
Andreas Huber20111aa2009-07-14 16:56:47 -07001708status_t MediaPlayerService::AudioCache::open(
1709 uint32_t sampleRate, int channelCount, int format, int bufferCount,
1710 AudioCallback cb, void *cookie)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001711{
Dave Sparks8eb80112009-12-09 20:20:26 -08001712 LOGV("open(%u, %d, %d, %d)", sampleRate, channelCount, format, bufferCount);
Dave Sparks8eb80112009-12-09 20:20:26 -08001713 if (mHeap->getHeapID() < 0) {
1714 return NO_INIT;
1715 }
Andreas Huber20111aa2009-07-14 16:56:47 -07001716
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001717 mSampleRate = sampleRate;
1718 mChannelCount = (uint16_t)channelCount;
1719 mFormat = (uint16_t)format;
1720 mMsecsPerFrame = 1.e3 / (float) sampleRate;
Andreas Huber7d5b8a72010-02-09 16:59:18 -08001721
1722 if (cb != NULL) {
1723 mCallbackThread = new CallbackThread(this, cb, cookie);
1724 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001725 return NO_ERROR;
1726}
1727
Andreas Huber7d5b8a72010-02-09 16:59:18 -08001728void MediaPlayerService::AudioCache::start() {
1729 if (mCallbackThread != NULL) {
1730 mCallbackThread->run("AudioCache callback");
1731 }
1732}
1733
1734void MediaPlayerService::AudioCache::stop() {
1735 if (mCallbackThread != NULL) {
1736 mCallbackThread->requestExitAndWait();
1737 }
1738}
1739
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001740ssize_t MediaPlayerService::AudioCache::write(const void* buffer, size_t size)
1741{
1742 LOGV("write(%p, %u)", buffer, size);
1743 if ((buffer == 0) || (size == 0)) return size;
1744
1745 uint8_t* p = static_cast<uint8_t*>(mHeap->getBase());
1746 if (p == NULL) return NO_INIT;
1747 p += mSize;
1748 LOGV("memcpy(%p, %p, %u)", p, buffer, size);
1749 if (mSize + size > mHeap->getSize()) {
1750 LOGE("Heap size overflow! req size: %d, max size: %d", (mSize + size), mHeap->getSize());
1751 size = mHeap->getSize() - mSize;
1752 }
1753 memcpy(p, buffer, size);
1754 mSize += size;
1755 return size;
1756}
1757
1758// call with lock held
1759status_t MediaPlayerService::AudioCache::wait()
1760{
1761 Mutex::Autolock lock(mLock);
Dave Sparks4bbc0ba2010-03-01 19:29:58 -08001762 while (!mCommandComplete) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001763 mSignal.wait(mLock);
1764 }
1765 mCommandComplete = false;
1766
1767 if (mError == NO_ERROR) {
1768 LOGV("wait - success");
1769 } else {
1770 LOGV("wait - error");
1771 }
1772 return mError;
1773}
1774
1775void MediaPlayerService::AudioCache::notify(void* cookie, int msg, int ext1, int ext2)
1776{
1777 LOGV("notify(%p, %d, %d, %d)", cookie, msg, ext1, ext2);
1778 AudioCache* p = static_cast<AudioCache*>(cookie);
1779
1780 // ignore buffering messages
Dave Sparks8eb80112009-12-09 20:20:26 -08001781 switch (msg)
1782 {
1783 case MEDIA_ERROR:
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001784 LOGE("Error %d, %d occurred", ext1, ext2);
1785 p->mError = ext1;
Dave Sparks8eb80112009-12-09 20:20:26 -08001786 break;
1787 case MEDIA_PREPARED:
1788 LOGV("prepared");
1789 break;
1790 case MEDIA_PLAYBACK_COMPLETE:
1791 LOGV("playback complete");
1792 break;
1793 default:
1794 LOGV("ignored");
1795 return;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001796 }
1797
1798 // wake up thread
Dave Sparksfe4c6f02010-03-02 12:56:37 -08001799 Mutex::Autolock lock(p->mLock);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001800 p->mCommandComplete = true;
1801 p->mSignal.signal();
1802}
1803
nikoa64c8c72009-07-20 15:07:26 -07001804} // namespace android