blob: 8e71700700c7f9c3a89ad8114ce8ac84956be1db [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"
59#include "VorbisPlayer.h"
60#include <media/PVPlayer.h>
Nicolas Catania14d27472009-07-13 14:37:49 -070061#include "TestPlayerStub.h"
Andreas Huber20111aa2009-07-14 16:56:47 -070062#include "StagefrightPlayer.h"
Andreas Huber20111aa2009-07-14 16:56:47 -070063
Andreas Huber20111aa2009-07-14 16:56:47 -070064#include <OMX.h>
Nicolas Catania14d27472009-07-13 14:37:49 -070065
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080066/* desktop Linux needs a little help with gettid() */
67#if defined(HAVE_GETTID) && !defined(HAVE_ANDROID_OS)
68#define __KERNEL__
69# include <linux/unistd.h>
70#ifdef _syscall0
71_syscall0(pid_t,gettid)
72#else
73pid_t gettid() { return syscall(__NR_gettid);}
74#endif
75#undef __KERNEL__
76#endif
77
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070078namespace {
nikoa64c8c72009-07-20 15:07:26 -070079using android::media::Metadata;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070080using android::status_t;
81using android::OK;
82using android::BAD_VALUE;
83using android::NOT_ENOUGH_DATA;
84using android::Parcel;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070085
86// Max number of entries in the filter.
87const int kMaxFilterSize = 64; // I pulled that out of thin air.
88
nikoa64c8c72009-07-20 15:07:26 -070089// FIXME: Move all the metadata related function in the Metadata.cpp
nikod608a812009-07-16 16:39:53 -070090
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070091
92// Unmarshall a filter from a Parcel.
93// Filter format in a parcel:
94//
95// 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
96// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
97// | number of entries (n) |
98// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
99// | metadata type 1 |
100// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
101// | metadata type 2 |
102// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
103// ....
104// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
105// | metadata type n |
106// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
107//
108// @param p Parcel that should start with a filter.
109// @param[out] filter On exit contains the list of metadata type to be
110// filtered.
111// @param[out] status On exit contains the status code to be returned.
112// @return true if the parcel starts with a valid filter.
113bool unmarshallFilter(const Parcel& p,
nikoa64c8c72009-07-20 15:07:26 -0700114 Metadata::Filter *filter,
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700115 status_t *status)
116{
Nicolas Catania48290382009-07-10 13:53:06 -0700117 int32_t val;
118 if (p.readInt32(&val) != OK)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700119 {
120 LOGE("Failed to read filter's length");
121 *status = NOT_ENOUGH_DATA;
122 return false;
123 }
124
Nicolas Catania48290382009-07-10 13:53:06 -0700125 if( val > kMaxFilterSize || val < 0)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700126 {
Nicolas Catania48290382009-07-10 13:53:06 -0700127 LOGE("Invalid filter len %d", val);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700128 *status = BAD_VALUE;
129 return false;
130 }
131
Nicolas Catania48290382009-07-10 13:53:06 -0700132 const size_t num = val;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700133
134 filter->clear();
Nicolas Catania48290382009-07-10 13:53:06 -0700135 filter->setCapacity(num);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700136
nikoa64c8c72009-07-20 15:07:26 -0700137 size_t size = num * sizeof(Metadata::Type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700138
Nicolas Catania48290382009-07-10 13:53:06 -0700139
140 if (p.dataAvail() < size)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700141 {
Nicolas Catania48290382009-07-10 13:53:06 -0700142 LOGE("Filter too short expected %d but got %d", size, p.dataAvail());
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700143 *status = NOT_ENOUGH_DATA;
144 return false;
145 }
146
nikoa64c8c72009-07-20 15:07:26 -0700147 const Metadata::Type *data =
148 static_cast<const Metadata::Type*>(p.readInplace(size));
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700149
Nicolas Catania48290382009-07-10 13:53:06 -0700150 if (NULL == data)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700151 {
152 LOGE("Filter had no data");
153 *status = BAD_VALUE;
154 return false;
155 }
156
157 // TODO: The stl impl of vector would be more efficient here
158 // because it degenerates into a memcpy on pod types. Try to
159 // replace later or use stl::set.
Nicolas Catania48290382009-07-10 13:53:06 -0700160 for (size_t i = 0; i < num; ++i)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700161 {
Nicolas Catania48290382009-07-10 13:53:06 -0700162 filter->add(*data);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700163 ++data;
164 }
165 *status = OK;
166 return true;
167}
168
Nicolas Catania48290382009-07-10 13:53:06 -0700169// @param filter Of metadata type.
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700170// @param val To be searched.
171// @return true if a match was found.
nikoa64c8c72009-07-20 15:07:26 -0700172bool findMetadata(const Metadata::Filter& filter, const int32_t val)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700173{
174 // Deal with empty and ANY right away
175 if (filter.isEmpty()) return false;
nikoa64c8c72009-07-20 15:07:26 -0700176 if (filter[0] == Metadata::kAny) return true;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700177
Nicolas Catania48290382009-07-10 13:53:06 -0700178 return filter.indexOf(val) >= 0;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700179}
180
181} // anonymous namespace
182
183
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800184namespace android {
185
186// TODO: Temp hack until we can register players
187typedef struct {
188 const char *extension;
189 const player_type playertype;
190} extmap;
191extmap FILE_EXTS [] = {
192 {".mid", SONIVOX_PLAYER},
193 {".midi", SONIVOX_PLAYER},
194 {".smf", SONIVOX_PLAYER},
195 {".xmf", SONIVOX_PLAYER},
196 {".imy", SONIVOX_PLAYER},
197 {".rtttl", SONIVOX_PLAYER},
198 {".rtx", SONIVOX_PLAYER},
199 {".ota", SONIVOX_PLAYER},
200 {".ogg", VORBIS_PLAYER},
201 {".oga", VORBIS_PLAYER},
202};
203
204// 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 -0800205/* static */ int MediaPlayerService::AudioOutput::mMinBufferCount = 4;
206/* static */ bool MediaPlayerService::AudioOutput::mIsOnEmulator = false;
207
208void MediaPlayerService::instantiate() {
209 defaultServiceManager()->addService(
210 String16("media.player"), new MediaPlayerService());
211}
212
213MediaPlayerService::MediaPlayerService()
214{
215 LOGV("MediaPlayerService created");
216 mNextConnId = 1;
217}
218
219MediaPlayerService::~MediaPlayerService()
220{
221 LOGV("MediaPlayerService destroyed");
222}
223
224sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(pid_t pid)
225{
Jean-Baptiste Queru6c5b2102009-03-21 11:40:18 -0700226#ifndef NO_OPENCORE
Gloria Wangdac6a312009-10-29 15:46:37 -0700227 sp<MediaRecorderClient> recorder = new MediaRecorderClient(this, pid);
228 wp<MediaRecorderClient> w = recorder;
229 Mutex::Autolock lock(mLock);
230 mMediaRecorderClients.add(w);
Jean-Baptiste Queru6c5b2102009-03-21 11:40:18 -0700231#else
232 sp<MediaRecorderClient> recorder = NULL;
233#endif
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800234 LOGV("Create new media recorder client from pid %d", pid);
235 return recorder;
236}
237
Gloria Wangdac6a312009-10-29 15:46:37 -0700238void MediaPlayerService::removeMediaRecorderClient(wp<MediaRecorderClient> client)
239{
240 Mutex::Autolock lock(mLock);
241 mMediaRecorderClients.remove(client);
242 LOGV("Delete media recorder client");
243}
244
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800245sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever(pid_t pid)
246{
247 sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
248 LOGV("Create new media retriever from pid %d", pid);
249 return retriever;
250}
251
252sp<IMediaPlayer> MediaPlayerService::create(pid_t pid, const sp<IMediaPlayerClient>& client, const char* url)
253{
254 int32_t connId = android_atomic_inc(&mNextConnId);
255 sp<Client> c = new Client(this, pid, connId, client);
256 LOGV("Create new client(%d) from pid %d, url=%s, connId=%d", connId, pid, url, connId);
257 if (NO_ERROR != c->setDataSource(url))
258 {
259 c.clear();
260 return c;
261 }
262 wp<Client> w = c;
263 Mutex::Autolock lock(mLock);
264 mClients.add(w);
265 return c;
266}
267
268sp<IMediaPlayer> MediaPlayerService::create(pid_t pid, const sp<IMediaPlayerClient>& client,
269 int fd, int64_t offset, int64_t length)
270{
271 int32_t connId = android_atomic_inc(&mNextConnId);
272 sp<Client> c = new Client(this, pid, connId, client);
273 LOGV("Create new client(%d) from pid %d, fd=%d, offset=%lld, length=%lld",
274 connId, pid, fd, offset, length);
275 if (NO_ERROR != c->setDataSource(fd, offset, length)) {
276 c.clear();
277 } else {
278 wp<Client> w = c;
279 Mutex::Autolock lock(mLock);
280 mClients.add(w);
281 }
282 ::close(fd);
283 return c;
284}
285
Andreas Huber318ad9c2009-10-15 13:46:54 -0700286sp<IOMX> MediaPlayerService::getOMX() {
287 Mutex::Autolock autoLock(mLock);
288
289 if (mOMX.get() == NULL) {
290 mOMX = new OMX;
291 }
292
293 return mOMX;
Andreas Huber20111aa2009-07-14 16:56:47 -0700294}
295
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800296status_t MediaPlayerService::AudioCache::dump(int fd, const Vector<String16>& args) const
297{
298 const size_t SIZE = 256;
299 char buffer[SIZE];
300 String8 result;
301
302 result.append(" AudioCache\n");
303 if (mHeap != 0) {
304 snprintf(buffer, 255, " heap base(%p), size(%d), flags(%d), device(%s)\n",
305 mHeap->getBase(), mHeap->getSize(), mHeap->getFlags(), mHeap->getDevice());
306 result.append(buffer);
307 }
308 snprintf(buffer, 255, " msec per frame(%f), channel count(%d), format(%d), frame count(%ld)\n",
309 mMsecsPerFrame, mChannelCount, mFormat, mFrameCount);
310 result.append(buffer);
311 snprintf(buffer, 255, " sample rate(%d), size(%d), error(%d), command complete(%s)\n",
312 mSampleRate, mSize, mError, mCommandComplete?"true":"false");
313 result.append(buffer);
314 ::write(fd, result.string(), result.size());
315 return NO_ERROR;
316}
317
318status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
319{
320 const size_t SIZE = 256;
321 char buffer[SIZE];
322 String8 result;
323
324 result.append(" AudioOutput\n");
325 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n",
326 mStreamType, mLeftVolume, mRightVolume);
327 result.append(buffer);
328 snprintf(buffer, 255, " msec per frame(%f), latency (%d)\n",
329 mMsecsPerFrame, mLatency);
330 result.append(buffer);
331 ::write(fd, result.string(), result.size());
332 if (mTrack != 0) {
333 mTrack->dump(fd, args);
334 }
335 return NO_ERROR;
336}
337
338status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args) const
339{
340 const size_t SIZE = 256;
341 char buffer[SIZE];
342 String8 result;
343 result.append(" Client\n");
344 snprintf(buffer, 255, " pid(%d), connId(%d), status(%d), looping(%s)\n",
345 mPid, mConnId, mStatus, mLoop?"true": "false");
346 result.append(buffer);
347 write(fd, result.string(), result.size());
348 if (mAudioOutput != 0) {
349 mAudioOutput->dump(fd, args);
350 }
351 write(fd, "\n", 1);
352 return NO_ERROR;
353}
354
355static int myTid() {
356#ifdef HAVE_GETTID
357 return gettid();
358#else
359 return getpid();
360#endif
361}
362
363#if defined(__arm__)
364extern "C" void get_malloc_leak_info(uint8_t** info, size_t* overallSize,
365 size_t* infoSize, size_t* totalMemory, size_t* backtraceSize);
366extern "C" void free_malloc_leak_info(uint8_t* info);
367
Andreas Huber1eea7f52009-10-27 15:50:04 -0700368// Use the String-class below instead of String8 to allocate all memory
369// beforehand and not reenter the heap while we are examining it...
370struct MyString8 {
371 static const size_t MAX_SIZE = 256 * 1024;
372
373 MyString8()
374 : mPtr((char *)malloc(MAX_SIZE)) {
375 *mPtr = '\0';
376 }
377
378 ~MyString8() {
379 free(mPtr);
380 }
381
382 void append(const char *s) {
383 strcat(mPtr, s);
384 }
385
386 const char *string() const {
387 return mPtr;
388 }
389
390 size_t size() const {
391 return strlen(mPtr);
392 }
393
394private:
395 char *mPtr;
396
397 MyString8(const MyString8 &);
398 MyString8 &operator=(const MyString8 &);
399};
400
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800401void memStatus(int fd, const Vector<String16>& args)
402{
403 const size_t SIZE = 256;
404 char buffer[SIZE];
Andreas Huber1eea7f52009-10-27 15:50:04 -0700405 MyString8 result;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800406
407 typedef struct {
408 size_t size;
409 size_t dups;
410 intptr_t * backtrace;
411 } AllocEntry;
412
413 uint8_t *info = NULL;
414 size_t overallSize = 0;
415 size_t infoSize = 0;
416 size_t totalMemory = 0;
417 size_t backtraceSize = 0;
418
419 get_malloc_leak_info(&info, &overallSize, &infoSize, &totalMemory, &backtraceSize);
420 if (info) {
421 uint8_t *ptr = info;
422 size_t count = overallSize / infoSize;
423
424 snprintf(buffer, SIZE, " Allocation count %i\n", count);
425 result.append(buffer);
426
427 AllocEntry * entries = new AllocEntry[count];
428
429 for (size_t i = 0; i < count; i++) {
430 // Each entry should be size_t, size_t, intptr_t[backtraceSize]
431 AllocEntry *e = &entries[i];
432
433 e->size = *reinterpret_cast<size_t *>(ptr);
434 ptr += sizeof(size_t);
435
436 e->dups = *reinterpret_cast<size_t *>(ptr);
437 ptr += sizeof(size_t);
438
439 e->backtrace = reinterpret_cast<intptr_t *>(ptr);
440 ptr += sizeof(intptr_t) * backtraceSize;
441 }
442
443 // Now we need to sort the entries. They come sorted by size but
444 // not by stack trace which causes problems using diff.
445 bool moved;
446 do {
447 moved = false;
448 for (size_t i = 0; i < (count - 1); i++) {
449 AllocEntry *e1 = &entries[i];
450 AllocEntry *e2 = &entries[i+1];
451
452 bool swap = e1->size < e2->size;
453 if (e1->size == e2->size) {
454 for(size_t j = 0; j < backtraceSize; j++) {
455 if (e1->backtrace[j] == e2->backtrace[j]) {
456 continue;
457 }
458 swap = e1->backtrace[j] < e2->backtrace[j];
459 break;
460 }
461 }
462 if (swap) {
463 AllocEntry t = entries[i];
464 entries[i] = entries[i+1];
465 entries[i+1] = t;
466 moved = true;
467 }
468 }
469 } while (moved);
470
471 for (size_t i = 0; i < count; i++) {
472 AllocEntry *e = &entries[i];
473
474 snprintf(buffer, SIZE, "size %8i, dup %4i", e->size, e->dups);
475 result.append(buffer);
476 for (size_t ct = 0; (ct < backtraceSize) && e->backtrace[ct]; ct++) {
477 if (ct) {
478 result.append(", ");
479 }
480 snprintf(buffer, SIZE, "0x%08x", e->backtrace[ct]);
481 result.append(buffer);
482 }
483 result.append("\n");
484 }
485
486 delete[] entries;
487 free_malloc_leak_info(info);
488 }
489
490 write(fd, result.string(), result.size());
491}
492#endif
493
494status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
495{
496 const size_t SIZE = 256;
497 char buffer[SIZE];
498 String8 result;
499 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
500 snprintf(buffer, SIZE, "Permission Denial: "
501 "can't dump MediaPlayerService from pid=%d, uid=%d\n",
502 IPCThreadState::self()->getCallingPid(),
503 IPCThreadState::self()->getCallingUid());
504 result.append(buffer);
505 } else {
506 Mutex::Autolock lock(mLock);
507 for (int i = 0, n = mClients.size(); i < n; ++i) {
508 sp<Client> c = mClients[i].promote();
509 if (c != 0) c->dump(fd, args);
510 }
Gloria Wangdac6a312009-10-29 15:46:37 -0700511 for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
512 result.append(" MediaRecorderClient\n");
513 sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
514 snprintf(buffer, 255, " pid(%d)\n\n", c->mPid);
515 result.append(buffer);
516 }
517
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800518 result.append(" Files opened and/or mapped:\n");
519 snprintf(buffer, SIZE, "/proc/%d/maps", myTid());
520 FILE *f = fopen(buffer, "r");
521 if (f) {
522 while (!feof(f)) {
523 fgets(buffer, SIZE, f);
524 if (strstr(buffer, " /sdcard/") ||
525 strstr(buffer, " /system/sounds/") ||
526 strstr(buffer, " /system/media/")) {
527 result.append(" ");
528 result.append(buffer);
529 }
530 }
531 fclose(f);
532 } else {
533 result.append("couldn't open ");
534 result.append(buffer);
535 result.append("\n");
536 }
537
538 snprintf(buffer, SIZE, "/proc/%d/fd", myTid());
539 DIR *d = opendir(buffer);
540 if (d) {
541 struct dirent *ent;
542 while((ent = readdir(d)) != NULL) {
543 if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
544 snprintf(buffer, SIZE, "/proc/%d/fd/%s", myTid(), ent->d_name);
545 struct stat s;
546 if (lstat(buffer, &s) == 0) {
547 if ((s.st_mode & S_IFMT) == S_IFLNK) {
548 char linkto[256];
549 int len = readlink(buffer, linkto, sizeof(linkto));
550 if(len > 0) {
551 if(len > 255) {
552 linkto[252] = '.';
553 linkto[253] = '.';
554 linkto[254] = '.';
555 linkto[255] = 0;
556 } else {
557 linkto[len] = 0;
558 }
559 if (strstr(linkto, "/sdcard/") == linkto ||
560 strstr(linkto, "/system/sounds/") == linkto ||
561 strstr(linkto, "/system/media/") == linkto) {
562 result.append(" ");
563 result.append(buffer);
564 result.append(" -> ");
565 result.append(linkto);
566 result.append("\n");
567 }
568 }
569 } else {
570 result.append(" unexpected type for ");
571 result.append(buffer);
572 result.append("\n");
573 }
574 }
575 }
576 }
577 closedir(d);
578 } else {
579 result.append("couldn't open ");
580 result.append(buffer);
581 result.append("\n");
582 }
583
584#if defined(__arm__)
585 bool dumpMem = false;
586 for (size_t i = 0; i < args.size(); i++) {
587 if (args[i] == String16("-m")) {
588 dumpMem = true;
589 }
590 }
591 if (dumpMem) {
592 memStatus(fd, args);
593 }
594#endif
595 }
596 write(fd, result.string(), result.size());
597 return NO_ERROR;
598}
599
600void MediaPlayerService::removeClient(wp<Client> client)
601{
602 Mutex::Autolock lock(mLock);
603 mClients.remove(client);
604}
605
606MediaPlayerService::Client::Client(const sp<MediaPlayerService>& service, pid_t pid,
607 int32_t connId, const sp<IMediaPlayerClient>& client)
608{
609 LOGV("Client(%d) constructor", connId);
610 mPid = pid;
611 mConnId = connId;
612 mService = service;
613 mClient = client;
614 mLoop = false;
615 mStatus = NO_INIT;
616#if CALLBACK_ANTAGONIZER
617 LOGD("create Antagonizer");
618 mAntagonizer = new Antagonizer(notify, this);
619#endif
620}
621
622MediaPlayerService::Client::~Client()
623{
624 LOGV("Client(%d) destructor pid = %d", mConnId, mPid);
625 mAudioOutput.clear();
626 wp<Client> client(this);
627 disconnect();
628 mService->removeClient(client);
629}
630
631void MediaPlayerService::Client::disconnect()
632{
633 LOGV("disconnect(%d) from pid %d", mConnId, mPid);
634 // grab local reference and clear main reference to prevent future
635 // access to object
636 sp<MediaPlayerBase> p;
637 {
638 Mutex::Autolock l(mLock);
639 p = mPlayer;
640 }
Dave Sparks795fa582009-03-24 17:57:12 -0700641 mClient.clear();
Andreas Huber20111aa2009-07-14 16:56:47 -0700642
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800643 mPlayer.clear();
644
645 // clear the notification to prevent callbacks to dead client
646 // and reset the player. We assume the player will serialize
647 // access to itself if necessary.
648 if (p != 0) {
649 p->setNotifyCallback(0, 0);
650#if CALLBACK_ANTAGONIZER
651 LOGD("kill Antagonizer");
652 mAntagonizer->kill();
653#endif
654 p->reset();
655 }
656
657 IPCThreadState::self()->flushCommands();
658}
659
Andreas Huber47f59cf2009-08-07 09:30:32 -0700660static player_type getDefaultPlayerType() {
Andreas Huber8f0e4aa2009-09-11 09:54:52 -0700661#if BUILD_WITH_FULL_STAGEFRIGHT
Andreas Huber47f59cf2009-08-07 09:30:32 -0700662 char value[PROPERTY_VALUE_MAX];
663 if (property_get("media.stagefright.enable-player", value, NULL)
664 && (!strcmp(value, "1") || !strcasecmp(value, "true"))) {
665 return STAGEFRIGHT_PLAYER;
666 }
Andreas Huber8f0e4aa2009-09-11 09:54:52 -0700667#endif
Andreas Huber47f59cf2009-08-07 09:30:32 -0700668
669 return PV_PLAYER;
670}
671
James Dong148c1a22009-09-06 14:29:45 -0700672player_type getPlayerType(int fd, int64_t offset, int64_t length)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800673{
674 char buf[20];
675 lseek(fd, offset, SEEK_SET);
676 read(fd, buf, sizeof(buf));
677 lseek(fd, offset, SEEK_SET);
678
679 long ident = *((long*)buf);
680
681 // Ogg vorbis?
682 if (ident == 0x5367674f) // 'OggS'
683 return VORBIS_PLAYER;
684
685 // Some kind of MIDI?
686 EAS_DATA_HANDLE easdata;
687 if (EAS_Init(&easdata) == EAS_SUCCESS) {
688 EAS_FILE locator;
689 locator.path = NULL;
690 locator.fd = fd;
691 locator.offset = offset;
692 locator.length = length;
693 EAS_HANDLE eashandle;
694 if (EAS_OpenFile(easdata, &locator, &eashandle) == EAS_SUCCESS) {
695 EAS_CloseFile(easdata, eashandle);
696 EAS_Shutdown(easdata);
697 return SONIVOX_PLAYER;
698 }
699 EAS_Shutdown(easdata);
700 }
701
Andreas Huber47f59cf2009-08-07 09:30:32 -0700702 return getDefaultPlayerType();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800703}
704
James Dong148c1a22009-09-06 14:29:45 -0700705player_type getPlayerType(const char* url)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800706{
Nicolas Catania14d27472009-07-13 14:37:49 -0700707 if (TestPlayerStub::canBeUsed(url)) {
708 return TEST_PLAYER;
709 }
710
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800711 // use MidiFile for MIDI extensions
712 int lenURL = strlen(url);
713 for (int i = 0; i < NELEM(FILE_EXTS); ++i) {
714 int len = strlen(FILE_EXTS[i].extension);
715 int start = lenURL - len;
716 if (start > 0) {
717 if (!strncmp(url + start, FILE_EXTS[i].extension, len)) {
718 return FILE_EXTS[i].playertype;
719 }
720 }
721 }
722
Andreas Huber47945ea2009-12-17 13:31:13 -0800723 if (!strncasecmp(url, "http://", 7)) {
724 // For now, we're going to use PV for http-based playback,
725 // until we can clear up a few more issues.
726 return PV_PLAYER;
727 }
728
Andreas Huber47f59cf2009-08-07 09:30:32 -0700729 return getDefaultPlayerType();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800730}
731
732static sp<MediaPlayerBase> createPlayer(player_type playerType, void* cookie,
733 notify_callback_f notifyFunc)
734{
735 sp<MediaPlayerBase> p;
736 switch (playerType) {
Jean-Baptiste Queru6c5b2102009-03-21 11:40:18 -0700737#ifndef NO_OPENCORE
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800738 case PV_PLAYER:
739 LOGV(" create PVPlayer");
740 p = new PVPlayer();
741 break;
Jean-Baptiste Queru6c5b2102009-03-21 11:40:18 -0700742#endif
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800743 case SONIVOX_PLAYER:
744 LOGV(" create MidiFile");
745 p = new MidiFile();
746 break;
747 case VORBIS_PLAYER:
748 LOGV(" create VorbisPlayer");
749 p = new VorbisPlayer();
750 break;
Andreas Huber8f0e4aa2009-09-11 09:54:52 -0700751#if BUILD_WITH_FULL_STAGEFRIGHT
Andreas Huber20111aa2009-07-14 16:56:47 -0700752 case STAGEFRIGHT_PLAYER:
753 LOGV(" create StagefrightPlayer");
754 p = new StagefrightPlayer;
755 break;
Andreas Huber8f0e4aa2009-09-11 09:54:52 -0700756#endif
Nicolas Catania14d27472009-07-13 14:37:49 -0700757 case TEST_PLAYER:
758 LOGV("Create Test Player stub");
759 p = new TestPlayerStub();
760 break;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800761 }
762 if (p != NULL) {
763 if (p->initCheck() == NO_ERROR) {
764 p->setNotifyCallback(cookie, notifyFunc);
765 } else {
766 p.clear();
767 }
768 }
769 if (p == NULL) {
770 LOGE("Failed to create player object");
771 }
772 return p;
773}
774
775sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
776{
777 // determine if we have the right player type
778 sp<MediaPlayerBase> p = mPlayer;
779 if ((p != NULL) && (p->playerType() != playerType)) {
780 LOGV("delete player");
781 p.clear();
782 }
783 if (p == NULL) {
784 p = android::createPlayer(playerType, this, notify);
785 }
786 return p;
787}
788
789status_t MediaPlayerService::Client::setDataSource(const char *url)
790{
791 LOGV("setDataSource(%s)", url);
792 if (url == NULL)
793 return UNKNOWN_ERROR;
794
795 if (strncmp(url, "content://", 10) == 0) {
796 // get a filedescriptor for the content Uri and
797 // pass it to the setDataSource(fd) method
798
799 String16 url16(url);
800 int fd = android::openContentProviderFile(url16);
801 if (fd < 0)
802 {
803 LOGE("Couldn't open fd for %s", url);
804 return UNKNOWN_ERROR;
805 }
806 setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
807 close(fd);
808 return mStatus;
809 } else {
810 player_type playerType = getPlayerType(url);
811 LOGV("player type = %d", playerType);
812
813 // create the right type of player
814 sp<MediaPlayerBase> p = createPlayer(playerType);
815 if (p == NULL) return NO_INIT;
816
817 if (!p->hardwareOutput()) {
818 mAudioOutput = new AudioOutput();
819 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
820 }
821
822 // now set data source
823 LOGV(" setDataSource");
824 mStatus = p->setDataSource(url);
Nicolas Catania14d27472009-07-13 14:37:49 -0700825 if (mStatus == NO_ERROR) {
826 mPlayer = p;
827 } else {
828 LOGE(" error: %d", mStatus);
829 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800830 return mStatus;
831 }
832}
833
834status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
835{
836 LOGV("setDataSource fd=%d, offset=%lld, length=%lld", fd, offset, length);
837 struct stat sb;
838 int ret = fstat(fd, &sb);
839 if (ret != 0) {
840 LOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
841 return UNKNOWN_ERROR;
842 }
843
844 LOGV("st_dev = %llu", sb.st_dev);
845 LOGV("st_mode = %u", sb.st_mode);
846 LOGV("st_uid = %lu", sb.st_uid);
847 LOGV("st_gid = %lu", sb.st_gid);
848 LOGV("st_size = %llu", sb.st_size);
849
850 if (offset >= sb.st_size) {
851 LOGE("offset error");
852 ::close(fd);
853 return UNKNOWN_ERROR;
854 }
855 if (offset + length > sb.st_size) {
856 length = sb.st_size - offset;
857 LOGV("calculated length = %lld", length);
858 }
859
860 player_type playerType = getPlayerType(fd, offset, length);
861 LOGV("player type = %d", playerType);
862
863 // create the right type of player
864 sp<MediaPlayerBase> p = createPlayer(playerType);
865 if (p == NULL) return NO_INIT;
866
867 if (!p->hardwareOutput()) {
868 mAudioOutput = new AudioOutput();
869 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
870 }
871
872 // now set data source
873 mStatus = p->setDataSource(fd, offset, length);
874 if (mStatus == NO_ERROR) mPlayer = p;
875 return mStatus;
876}
877
878status_t MediaPlayerService::Client::setVideoSurface(const sp<ISurface>& surface)
879{
880 LOGV("[%d] setVideoSurface(%p)", mConnId, surface.get());
881 sp<MediaPlayerBase> p = getPlayer();
882 if (p == 0) return UNKNOWN_ERROR;
883 return p->setVideoSurface(surface);
884}
885
Nicolas Catania1d187f12009-05-12 23:25:55 -0700886status_t MediaPlayerService::Client::invoke(const Parcel& request,
887 Parcel *reply)
888{
889 sp<MediaPlayerBase> p = getPlayer();
890 if (p == NULL) return UNKNOWN_ERROR;
891 return p->invoke(request, reply);
892}
893
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700894// This call doesn't need to access the native player.
895status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
896{
897 status_t status;
nikoa64c8c72009-07-20 15:07:26 -0700898 media::Metadata::Filter allow, drop;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700899
Nicolas Catania48290382009-07-10 13:53:06 -0700900 if (unmarshallFilter(filter, &allow, &status) &&
901 unmarshallFilter(filter, &drop, &status)) {
902 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700903
904 mMetadataAllow = allow;
905 mMetadataDrop = drop;
906 }
907 return status;
908}
909
Nicolas Catania48290382009-07-10 13:53:06 -0700910status_t MediaPlayerService::Client::getMetadata(
911 bool update_only, bool apply_filter, Parcel *reply)
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700912{
nikoa64c8c72009-07-20 15:07:26 -0700913 sp<MediaPlayerBase> player = getPlayer();
914 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania48290382009-07-10 13:53:06 -0700915
nikod608a812009-07-16 16:39:53 -0700916 status_t status;
917 // Placeholder for the return code, updated by the caller.
918 reply->writeInt32(-1);
919
nikoa64c8c72009-07-20 15:07:26 -0700920 media::Metadata::Filter ids;
Nicolas Catania48290382009-07-10 13:53:06 -0700921
922 // We don't block notifications while we fetch the data. We clear
923 // mMetadataUpdated first so we don't lose notifications happening
924 // during the rest of this call.
925 {
926 Mutex::Autolock lock(mLock);
927 if (update_only) {
nikod608a812009-07-16 16:39:53 -0700928 ids = mMetadataUpdated;
Nicolas Catania48290382009-07-10 13:53:06 -0700929 }
930 mMetadataUpdated.clear();
931 }
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700932
nikoa64c8c72009-07-20 15:07:26 -0700933 media::Metadata metadata(reply);
Nicolas Catania48290382009-07-10 13:53:06 -0700934
nikoa64c8c72009-07-20 15:07:26 -0700935 metadata.appendHeader();
936 status = player->getMetadata(ids, reply);
nikod608a812009-07-16 16:39:53 -0700937
938 if (status != OK) {
nikoa64c8c72009-07-20 15:07:26 -0700939 metadata.resetParcel();
nikod608a812009-07-16 16:39:53 -0700940 LOGE("getMetadata failed %d", status);
941 return status;
942 }
943
944 // FIXME: Implement filtering on the result. Not critical since
945 // filtering takes place on the update notifications already. This
946 // would be when all the metadata are fetch and a filter is set.
947
nikod608a812009-07-16 16:39:53 -0700948 // Everything is fine, update the metadata length.
nikoa64c8c72009-07-20 15:07:26 -0700949 metadata.updateLength();
nikod608a812009-07-16 16:39:53 -0700950 return OK;
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700951}
952
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800953status_t MediaPlayerService::Client::prepareAsync()
954{
955 LOGV("[%d] prepareAsync", mConnId);
956 sp<MediaPlayerBase> p = getPlayer();
957 if (p == 0) return UNKNOWN_ERROR;
958 status_t ret = p->prepareAsync();
959#if CALLBACK_ANTAGONIZER
960 LOGD("start Antagonizer");
961 if (ret == NO_ERROR) mAntagonizer->start();
962#endif
963 return ret;
964}
965
966status_t MediaPlayerService::Client::start()
967{
968 LOGV("[%d] start", mConnId);
969 sp<MediaPlayerBase> p = getPlayer();
970 if (p == 0) return UNKNOWN_ERROR;
971 p->setLooping(mLoop);
972 return p->start();
973}
974
975status_t MediaPlayerService::Client::stop()
976{
977 LOGV("[%d] stop", mConnId);
978 sp<MediaPlayerBase> p = getPlayer();
979 if (p == 0) return UNKNOWN_ERROR;
980 return p->stop();
981}
982
983status_t MediaPlayerService::Client::pause()
984{
985 LOGV("[%d] pause", mConnId);
986 sp<MediaPlayerBase> p = getPlayer();
987 if (p == 0) return UNKNOWN_ERROR;
988 return p->pause();
989}
990
991status_t MediaPlayerService::Client::isPlaying(bool* state)
992{
993 *state = false;
994 sp<MediaPlayerBase> p = getPlayer();
995 if (p == 0) return UNKNOWN_ERROR;
996 *state = p->isPlaying();
997 LOGV("[%d] isPlaying: %d", mConnId, *state);
998 return NO_ERROR;
999}
1000
1001status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
1002{
1003 LOGV("getCurrentPosition");
1004 sp<MediaPlayerBase> p = getPlayer();
1005 if (p == 0) return UNKNOWN_ERROR;
1006 status_t ret = p->getCurrentPosition(msec);
1007 if (ret == NO_ERROR) {
1008 LOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
1009 } else {
1010 LOGE("getCurrentPosition returned %d", ret);
1011 }
1012 return ret;
1013}
1014
1015status_t MediaPlayerService::Client::getDuration(int *msec)
1016{
1017 LOGV("getDuration");
1018 sp<MediaPlayerBase> p = getPlayer();
1019 if (p == 0) return UNKNOWN_ERROR;
1020 status_t ret = p->getDuration(msec);
1021 if (ret == NO_ERROR) {
1022 LOGV("[%d] getDuration = %d", mConnId, *msec);
1023 } else {
1024 LOGE("getDuration returned %d", ret);
1025 }
1026 return ret;
1027}
1028
1029status_t MediaPlayerService::Client::seekTo(int msec)
1030{
1031 LOGV("[%d] seekTo(%d)", mConnId, msec);
1032 sp<MediaPlayerBase> p = getPlayer();
1033 if (p == 0) return UNKNOWN_ERROR;
1034 return p->seekTo(msec);
1035}
1036
1037status_t MediaPlayerService::Client::reset()
1038{
1039 LOGV("[%d] reset", mConnId);
1040 sp<MediaPlayerBase> p = getPlayer();
1041 if (p == 0) return UNKNOWN_ERROR;
1042 return p->reset();
1043}
1044
1045status_t MediaPlayerService::Client::setAudioStreamType(int type)
1046{
1047 LOGV("[%d] setAudioStreamType(%d)", mConnId, type);
1048 // TODO: for hardware output, call player instead
1049 Mutex::Autolock l(mLock);
1050 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1051 return NO_ERROR;
1052}
1053
1054status_t MediaPlayerService::Client::setLooping(int loop)
1055{
1056 LOGV("[%d] setLooping(%d)", mConnId, loop);
1057 mLoop = loop;
1058 sp<MediaPlayerBase> p = getPlayer();
1059 if (p != 0) return p->setLooping(loop);
1060 return NO_ERROR;
1061}
1062
1063status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1064{
1065 LOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
1066 // TODO: for hardware output, call player instead
1067 Mutex::Autolock l(mLock);
1068 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1069 return NO_ERROR;
1070}
1071
Nicolas Catania48290382009-07-10 13:53:06 -07001072
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001073void MediaPlayerService::Client::notify(void* cookie, int msg, int ext1, int ext2)
1074{
1075 Client* client = static_cast<Client*>(cookie);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001076
1077 if (MEDIA_INFO == msg &&
Nicolas Catania48290382009-07-10 13:53:06 -07001078 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikoa64c8c72009-07-20 15:07:26 -07001079 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania48290382009-07-10 13:53:06 -07001080
1081 if(client->shouldDropMetadata(metadata_type)) {
1082 return;
1083 }
1084
1085 // Update the list of metadata that have changed. getMetadata
1086 // also access mMetadataUpdated and clears it.
1087 client->addNewMetadataUpdate(metadata_type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001088 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001089 LOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
1090 client->mClient->notify(msg, ext1, ext2);
1091}
1092
Nicolas Catania48290382009-07-10 13:53:06 -07001093
nikoa64c8c72009-07-20 15:07:26 -07001094bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001095{
Nicolas Catania48290382009-07-10 13:53:06 -07001096 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001097
Nicolas Catania48290382009-07-10 13:53:06 -07001098 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001099 return true;
1100 }
1101
Nicolas Catania48290382009-07-10 13:53:06 -07001102 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001103 return false;
Nicolas Catania48290382009-07-10 13:53:06 -07001104 } else {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001105 return true;
1106 }
1107}
1108
Nicolas Catania48290382009-07-10 13:53:06 -07001109
nikoa64c8c72009-07-20 15:07:26 -07001110void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania48290382009-07-10 13:53:06 -07001111 Mutex::Autolock lock(mLock);
1112 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1113 mMetadataUpdated.add(metadata_type);
1114 }
1115}
1116
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001117#if CALLBACK_ANTAGONIZER
1118const int Antagonizer::interval = 10000; // 10 msecs
1119
1120Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1121 mExit(false), mActive(false), mClient(client), mCb(cb)
1122{
1123 createThread(callbackThread, this);
1124}
1125
1126void Antagonizer::kill()
1127{
1128 Mutex::Autolock _l(mLock);
1129 mActive = false;
1130 mExit = true;
1131 mCondition.wait(mLock);
1132}
1133
1134int Antagonizer::callbackThread(void* user)
1135{
1136 LOGD("Antagonizer started");
1137 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1138 while (!p->mExit) {
1139 if (p->mActive) {
1140 LOGV("send event");
1141 p->mCb(p->mClient, 0, 0, 0);
1142 }
1143 usleep(interval);
1144 }
1145 Mutex::Autolock _l(p->mLock);
1146 p->mCondition.signal();
1147 LOGD("Antagonizer stopped");
1148 return 0;
1149}
1150#endif
1151
1152static size_t kDefaultHeapSize = 1024 * 1024; // 1MB
1153
1154sp<IMemory> MediaPlayerService::decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1155{
1156 LOGV("decode(%s)", url);
1157 sp<MemoryBase> mem;
1158 sp<MediaPlayerBase> player;
1159
1160 // Protect our precious, precious DRMd ringtones by only allowing
1161 // decoding of http, but not filesystem paths or content Uris.
1162 // If the application wants to decode those, it should open a
1163 // filedescriptor for them and use that.
1164 if (url != NULL && strncmp(url, "http://", 7) != 0) {
1165 LOGD("Can't decode %s by path, use filedescriptor instead", url);
1166 return mem;
1167 }
1168
1169 player_type playerType = getPlayerType(url);
1170 LOGV("player type = %d", playerType);
1171
1172 // create the right type of player
1173 sp<AudioCache> cache = new AudioCache(url);
1174 player = android::createPlayer(playerType, cache.get(), cache->notify);
1175 if (player == NULL) goto Exit;
1176 if (player->hardwareOutput()) goto Exit;
1177
1178 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1179
1180 // set data source
1181 if (player->setDataSource(url) != NO_ERROR) goto Exit;
1182
1183 LOGV("prepare");
1184 player->prepareAsync();
1185
1186 LOGV("wait for prepare");
1187 if (cache->wait() != NO_ERROR) goto Exit;
1188
1189 LOGV("start");
1190 player->start();
1191
1192 LOGV("wait for playback complete");
1193 if (cache->wait() != NO_ERROR) goto Exit;
1194
1195 mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1196 *pSampleRate = cache->sampleRate();
1197 *pNumChannels = cache->channelCount();
1198 *pFormat = cache->format();
1199 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1200
1201Exit:
1202 if (player != 0) player->reset();
1203 return mem;
1204}
1205
1206sp<IMemory> MediaPlayerService::decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1207{
1208 LOGV("decode(%d, %lld, %lld)", fd, offset, length);
1209 sp<MemoryBase> mem;
1210 sp<MediaPlayerBase> player;
1211
1212 player_type playerType = getPlayerType(fd, offset, length);
1213 LOGV("player type = %d", playerType);
1214
1215 // create the right type of player
1216 sp<AudioCache> cache = new AudioCache("decode_fd");
1217 player = android::createPlayer(playerType, cache.get(), cache->notify);
1218 if (player == NULL) goto Exit;
1219 if (player->hardwareOutput()) goto Exit;
1220
1221 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1222
1223 // set data source
1224 if (player->setDataSource(fd, offset, length) != NO_ERROR) goto Exit;
1225
1226 LOGV("prepare");
1227 player->prepareAsync();
1228
1229 LOGV("wait for prepare");
1230 if (cache->wait() != NO_ERROR) goto Exit;
1231
1232 LOGV("start");
1233 player->start();
1234
1235 LOGV("wait for playback complete");
1236 if (cache->wait() != NO_ERROR) goto Exit;
1237
1238 mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1239 *pSampleRate = cache->sampleRate();
1240 *pNumChannels = cache->channelCount();
1241 *pFormat = cache->format();
1242 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1243
1244Exit:
1245 if (player != 0) player->reset();
1246 ::close(fd);
1247 return mem;
1248}
1249
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001250/*
1251 * Avert your eyes, ugly hack ahead.
1252 * The following is to support music visualizations.
1253 */
1254
1255static const int NUMVIZBUF = 32;
1256static const int VIZBUFFRAMES = 1024;
1257static const int TOTALBUFTIMEMSEC = NUMVIZBUF * VIZBUFFRAMES * 1000 / 44100;
1258
1259static bool gotMem = false;
1260static sp<MemoryBase> mem[NUMVIZBUF];
1261static uint64_t timeStamp[NUMVIZBUF];
1262static uint64_t lastReadTime;
1263static uint64_t lastWriteTime;
1264static int writeIdx = 0;
1265
1266static void allocVizBufs() {
1267 if (!gotMem) {
1268 for (int i=0;i<NUMVIZBUF;i++) {
1269 sp<MemoryHeapBase> heap = new MemoryHeapBase(VIZBUFFRAMES*2, 0, "snooper");
1270 mem[i] = new MemoryBase(heap, 0, heap->getSize());
1271 timeStamp[i] = 0;
1272 }
1273 gotMem = true;
1274 }
1275}
1276
1277
1278/*
1279 * Get a buffer of audio data that is about to be played.
1280 * We don't synchronize this because in practice the writer
1281 * is ahead of the reader, and even if we did happen to catch
1282 * a buffer while it's being written, it's just a visualization,
1283 * so no harm done.
1284 */
1285static sp<MemoryBase> getVizBuffer() {
1286
1287 allocVizBufs();
1288
1289 lastReadTime = uptimeMillis() + 100; // account for renderer delay (we shouldn't be doing this here)
1290
1291 // if there is no recent buffer (yet), just return empty handed
1292 if (lastWriteTime + TOTALBUFTIMEMSEC < lastReadTime) {
1293 //LOGI("@@@@ no audio data to look at yet");
1294 return NULL;
1295 }
1296
1297 char buf[200];
1298
1299 int closestIdx = -1;
1300 uint32_t closestTime = 0x7ffffff;
1301
1302 for (int i = 0; i < NUMVIZBUF; i++) {
1303 uint64_t tsi = timeStamp[i];
1304 uint64_t diff = tsi > lastReadTime ? tsi - lastReadTime : lastReadTime - tsi;
1305 if (diff < closestTime) {
1306 closestIdx = i;
1307 closestTime = diff;
1308 }
1309 }
1310
1311
1312 if (closestIdx >= 0) {
1313 //LOGI("@@@ return buffer %d, %d/%d", closestIdx, uint32_t(lastReadTime), uint32_t(timeStamp[closestIdx]));
1314 return mem[closestIdx];
1315 }
1316
1317 // we won't get here, since we either bailed out early, or got a buffer
1318 LOGD("Didn't expect to be here");
1319 return NULL;
1320}
1321
1322static void storeVizBuf(const void *data, int len, uint64_t time) {
1323 // Copy the data in to the visualizer buffer
1324 // Assume a 16 bit stereo source for now.
1325 short *viz = (short*)mem[writeIdx]->pointer();
1326 short *src = (short*)data;
1327 for (int i = 0; i < VIZBUFFRAMES; i++) {
1328 // Degrade quality by mixing to mono and clearing the lowest 3 bits.
1329 // This should still be good enough for a visualization
1330 *viz++ = ((int(src[0]) + int(src[1])) >> 1) & ~0x7;
1331 src += 2;
1332 }
1333 timeStamp[writeIdx++] = time;
1334 if (writeIdx >= NUMVIZBUF) {
1335 writeIdx = 0;
1336 }
1337}
1338
1339static void makeVizBuffers(const char *data, int len, uint64_t time) {
1340
1341 allocVizBufs();
1342
1343 uint64_t startTime = time;
1344 const int frameSize = 4; // 16 bit stereo sample is 4 bytes
1345 while (len >= VIZBUFFRAMES * frameSize) {
1346 storeVizBuf(data, len, time);
1347 data += VIZBUFFRAMES * frameSize;
1348 len -= VIZBUFFRAMES * frameSize;
1349 time += 1000 * VIZBUFFRAMES / 44100;
1350 }
1351 //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"
1363MediaPlayerService::AudioOutput::AudioOutput()
Andreas Huber20111aa2009-07-14 16:56:47 -07001364 : mCallback(NULL),
1365 mCallbackCookie(NULL) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001366 mTrack = 0;
1367 mStreamType = AudioSystem::MUSIC;
1368 mLeftVolume = 1.0;
1369 mRightVolume = 1.0;
1370 mLatency = 0;
1371 mMsecsPerFrame = 0;
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001372 mNumFramesWritten = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001373 setMinBufferCount();
1374}
1375
1376MediaPlayerService::AudioOutput::~AudioOutput()
1377{
1378 close();
1379}
1380
1381void MediaPlayerService::AudioOutput::setMinBufferCount()
1382{
1383 char value[PROPERTY_VALUE_MAX];
1384 if (property_get("ro.kernel.qemu", value, 0)) {
1385 mIsOnEmulator = true;
1386 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1387 }
1388}
1389
1390bool MediaPlayerService::AudioOutput::isOnEmulator()
1391{
1392 setMinBufferCount();
1393 return mIsOnEmulator;
1394}
1395
1396int MediaPlayerService::AudioOutput::getMinBufferCount()
1397{
1398 setMinBufferCount();
1399 return mMinBufferCount;
1400}
1401
1402ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1403{
1404 if (mTrack == 0) return NO_INIT;
1405 return mTrack->frameCount() * frameSize();
1406}
1407
1408ssize_t MediaPlayerService::AudioOutput::frameCount() const
1409{
1410 if (mTrack == 0) return NO_INIT;
1411 return mTrack->frameCount();
1412}
1413
1414ssize_t MediaPlayerService::AudioOutput::channelCount() const
1415{
1416 if (mTrack == 0) return NO_INIT;
1417 return mTrack->channelCount();
1418}
1419
1420ssize_t MediaPlayerService::AudioOutput::frameSize() const
1421{
1422 if (mTrack == 0) return NO_INIT;
1423 return mTrack->frameSize();
1424}
1425
1426uint32_t MediaPlayerService::AudioOutput::latency () const
1427{
1428 return mLatency;
1429}
1430
1431float MediaPlayerService::AudioOutput::msecsPerFrame() const
1432{
1433 return mMsecsPerFrame;
1434}
1435
Andreas Huber20111aa2009-07-14 16:56:47 -07001436status_t MediaPlayerService::AudioOutput::open(
1437 uint32_t sampleRate, int channelCount, int format, int bufferCount,
1438 AudioCallback cb, void *cookie)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001439{
Andreas Huber20111aa2009-07-14 16:56:47 -07001440 mCallback = cb;
1441 mCallbackCookie = cookie;
1442
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001443 // Check argument "bufferCount" against the mininum buffer count
1444 if (bufferCount < mMinBufferCount) {
1445 LOGD("bufferCount (%d) is too small and increased to %d", bufferCount, mMinBufferCount);
1446 bufferCount = mMinBufferCount;
1447
1448 }
1449 LOGV("open(%u, %d, %d, %d)", sampleRate, channelCount, format, bufferCount);
1450 if (mTrack) close();
1451 int afSampleRate;
1452 int afFrameCount;
1453 int frameCount;
1454
1455 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1456 return NO_INIT;
1457 }
1458 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1459 return NO_INIT;
1460 }
1461
1462 frameCount = (sampleRate*afFrameCount*bufferCount)/afSampleRate;
Andreas Huber20111aa2009-07-14 16:56:47 -07001463
1464 AudioTrack *t;
1465 if (mCallback != NULL) {
1466 t = new AudioTrack(
Eric Laurentc2f1f072009-07-17 12:17:14 -07001467 mStreamType,
1468 sampleRate,
1469 format,
1470 (channelCount == 2) ? AudioSystem::CHANNEL_OUT_STEREO : AudioSystem::CHANNEL_OUT_MONO,
1471 frameCount,
1472 0 /* flags */,
1473 CallbackWrapper,
1474 this);
Andreas Huber20111aa2009-07-14 16:56:47 -07001475 } else {
1476 t = new AudioTrack(
Eric Laurentc2f1f072009-07-17 12:17:14 -07001477 mStreamType,
1478 sampleRate,
1479 format,
1480 (channelCount == 2) ? AudioSystem::CHANNEL_OUT_STEREO : AudioSystem::CHANNEL_OUT_MONO,
1481 frameCount);
Andreas Huber20111aa2009-07-14 16:56:47 -07001482 }
1483
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001484 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1485 LOGE("Unable to create audio track");
1486 delete t;
1487 return NO_INIT;
1488 }
1489
1490 LOGV("setVolume");
1491 t->setVolume(mLeftVolume, mRightVolume);
1492 mMsecsPerFrame = 1.e3 / (float) sampleRate;
Dave Sparks1d711f62009-12-03 10:13:32 -08001493 mLatency = t->latency();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001494 mTrack = t;
1495 return NO_ERROR;
1496}
1497
1498void MediaPlayerService::AudioOutput::start()
1499{
1500 LOGV("start");
1501 if (mTrack) {
1502 mTrack->setVolume(mLeftVolume, mRightVolume);
1503 mTrack->start();
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001504 mTrack->getPosition(&mNumFramesWritten);
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001505 }
1506}
1507
1508ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size)
1509{
Andreas Huber20111aa2009-07-14 16:56:47 -07001510 LOG_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
1511
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001512 //LOGV("write(%p, %u)", buffer, size);
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001513 if (mTrack) {
1514 // Only make visualization buffers if anyone recently requested visualization data
1515 uint64_t now = uptimeMillis();
1516 if (lastReadTime + TOTALBUFTIMEMSEC >= now) {
1517 // Based on the current play counter, the number of frames written and
1518 // the current real time we can calculate the approximate real start
1519 // time of the buffer we're about to write.
1520 uint32_t pos;
1521 mTrack->getPosition(&pos);
1522
1523 // we're writing ahead by this many frames:
1524 int ahead = mNumFramesWritten - pos;
1525 //LOGI("@@@ written: %d, playpos: %d, latency: %d", mNumFramesWritten, pos, mTrack->latency());
1526 // which is this many milliseconds, assuming 44100 Hz:
1527 ahead /= 44;
1528
1529 makeVizBuffers((const char*)buffer, size, now + ahead + mTrack->latency());
1530 lastWriteTime = now;
1531 }
1532 ssize_t ret = mTrack->write(buffer, size);
1533 mNumFramesWritten += ret / 4; // assume 16 bit stereo
1534 return ret;
1535 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001536 return NO_INIT;
1537}
1538
1539void MediaPlayerService::AudioOutput::stop()
1540{
1541 LOGV("stop");
1542 if (mTrack) mTrack->stop();
Marco Nelissen10dbb8e2009-09-20 10:42:13 -07001543 lastWriteTime = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001544}
1545
1546void MediaPlayerService::AudioOutput::flush()
1547{
1548 LOGV("flush");
1549 if (mTrack) mTrack->flush();
1550}
1551
1552void MediaPlayerService::AudioOutput::pause()
1553{
1554 LOGV("pause");
1555 if (mTrack) mTrack->pause();
Marco Nelissen6741eb82009-11-02 13:52:11 -08001556 lastWriteTime = 0;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001557}
1558
1559void MediaPlayerService::AudioOutput::close()
1560{
1561 LOGV("close");
1562 delete mTrack;
1563 mTrack = 0;
1564}
1565
1566void MediaPlayerService::AudioOutput::setVolume(float left, float right)
1567{
1568 LOGV("setVolume(%f, %f)", left, right);
1569 mLeftVolume = left;
1570 mRightVolume = right;
1571 if (mTrack) {
1572 mTrack->setVolume(left, right);
1573 }
1574}
1575
Andreas Huber20111aa2009-07-14 16:56:47 -07001576// static
1577void MediaPlayerService::AudioOutput::CallbackWrapper(
1578 int event, void *cookie, void *info) {
1579 if (event != AudioTrack::EVENT_MORE_DATA) {
1580 return;
1581 }
1582
1583 AudioOutput *me = (AudioOutput *)cookie;
1584 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
1585
1586 (*me->mCallback)(
1587 me, buffer->raw, buffer->size, me->mCallbackCookie);
1588}
1589
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001590#undef LOG_TAG
1591#define LOG_TAG "AudioCache"
1592MediaPlayerService::AudioCache::AudioCache(const char* name) :
1593 mChannelCount(0), mFrameCount(1024), mSampleRate(0), mSize(0),
1594 mError(NO_ERROR), mCommandComplete(false)
1595{
1596 // create ashmem heap
1597 mHeap = new MemoryHeapBase(kDefaultHeapSize, 0, name);
1598}
1599
1600uint32_t MediaPlayerService::AudioCache::latency () const
1601{
1602 return 0;
1603}
1604
1605float MediaPlayerService::AudioCache::msecsPerFrame() const
1606{
1607 return mMsecsPerFrame;
1608}
1609
Andreas Huber20111aa2009-07-14 16:56:47 -07001610status_t MediaPlayerService::AudioCache::open(
1611 uint32_t sampleRate, int channelCount, int format, int bufferCount,
1612 AudioCallback cb, void *cookie)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001613{
Dave Sparks8eb80112009-12-09 20:20:26 -08001614 LOGV("open(%u, %d, %d, %d)", sampleRate, channelCount, format, bufferCount);
Andreas Huber20111aa2009-07-14 16:56:47 -07001615 if (cb != NULL) {
1616 return UNKNOWN_ERROR; // TODO: implement this.
1617 }
Dave Sparks8eb80112009-12-09 20:20:26 -08001618 if (mHeap->getHeapID() < 0) {
1619 return NO_INIT;
1620 }
Andreas Huber20111aa2009-07-14 16:56:47 -07001621
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001622 mSampleRate = sampleRate;
1623 mChannelCount = (uint16_t)channelCount;
1624 mFormat = (uint16_t)format;
1625 mMsecsPerFrame = 1.e3 / (float) sampleRate;
1626 return NO_ERROR;
1627}
1628
1629ssize_t MediaPlayerService::AudioCache::write(const void* buffer, size_t size)
1630{
1631 LOGV("write(%p, %u)", buffer, size);
1632 if ((buffer == 0) || (size == 0)) return size;
1633
1634 uint8_t* p = static_cast<uint8_t*>(mHeap->getBase());
1635 if (p == NULL) return NO_INIT;
1636 p += mSize;
1637 LOGV("memcpy(%p, %p, %u)", p, buffer, size);
1638 if (mSize + size > mHeap->getSize()) {
1639 LOGE("Heap size overflow! req size: %d, max size: %d", (mSize + size), mHeap->getSize());
1640 size = mHeap->getSize() - mSize;
1641 }
1642 memcpy(p, buffer, size);
1643 mSize += size;
1644 return size;
1645}
1646
1647// call with lock held
1648status_t MediaPlayerService::AudioCache::wait()
1649{
1650 Mutex::Autolock lock(mLock);
1651 if (!mCommandComplete) {
1652 mSignal.wait(mLock);
1653 }
1654 mCommandComplete = false;
1655
1656 if (mError == NO_ERROR) {
1657 LOGV("wait - success");
1658 } else {
1659 LOGV("wait - error");
1660 }
1661 return mError;
1662}
1663
1664void MediaPlayerService::AudioCache::notify(void* cookie, int msg, int ext1, int ext2)
1665{
1666 LOGV("notify(%p, %d, %d, %d)", cookie, msg, ext1, ext2);
1667 AudioCache* p = static_cast<AudioCache*>(cookie);
1668
1669 // ignore buffering messages
Dave Sparks8eb80112009-12-09 20:20:26 -08001670 switch (msg)
1671 {
1672 case MEDIA_ERROR:
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001673 LOGE("Error %d, %d occurred", ext1, ext2);
1674 p->mError = ext1;
Dave Sparks8eb80112009-12-09 20:20:26 -08001675 break;
1676 case MEDIA_PREPARED:
1677 LOGV("prepared");
1678 break;
1679 case MEDIA_PLAYBACK_COMPLETE:
1680 LOGV("playback complete");
1681 break;
1682 default:
1683 LOGV("ignored");
1684 return;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001685 }
1686
1687 // wake up thread
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001688 p->mCommandComplete = true;
1689 p->mSignal.signal();
1690}
1691
nikoa64c8c72009-07-20 15:07:26 -07001692} // namespace android