blob: ab759dff1a503f3aa6d1548f877e58cd0d80eefb [file] [log] [blame]
The Android Open Source Project9066cfe2009-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 Agopiana650aaa2009-06-03 17:32:49 -070030
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031#include <cutils/atomic.h>
Nicolas Catania8f5fcab2009-07-13 14:37:49 -070032#include <cutils/properties.h> // for property_get
Mathias Agopiana650aaa2009-06-03 17:32:49 -070033
34#include <utils/misc.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035
36#include <android_runtime/ActivityManager.h>
Mathias Agopiana650aaa2009-06-03 17:32:49 -070037
Mathias Agopian07952722009-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 Catania20cb94e2009-05-12 23:25:55 -070042#include <utils/Errors.h> // for status_t
43#include <utils/String8.h>
Marco Nelissenc39d2e32009-09-20 10:42:13 -070044#include <utils/SystemClock.h>
Nicolas Catania20cb94e2009-05-12 23:25:55 -070045#include <utils/Vector.h>
The Android Open Source Project9066cfe2009-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>
nikobc726922009-07-20 15:07:26 -070051#include <media/Metadata.h>
The Android Open Source Project9066cfe2009-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 Catania8f5fcab2009-07-13 14:37:49 -070061#include "TestPlayerStub.h"
Andreas Hubere46b7be2009-07-14 16:56:47 -070062#include "StagefrightPlayer.h"
Andreas Hubere46b7be2009-07-14 16:56:47 -070063
Andreas Hubere46b7be2009-07-14 16:56:47 -070064#include <OMX.h>
Nicolas Catania8f5fcab2009-07-13 14:37:49 -070065
The Android Open Source Project9066cfe2009-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 Cataniab2c69392009-07-08 08:57:42 -070078namespace {
nikobc726922009-07-20 15:07:26 -070079using android::media::Metadata;
Nicolas Cataniab2c69392009-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 Cataniab2c69392009-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
nikobc726922009-07-20 15:07:26 -070089// FIXME: Move all the metadata related function in the Metadata.cpp
niko89948372009-07-16 16:39:53 -070090
Nicolas Cataniab2c69392009-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,
nikobc726922009-07-20 15:07:26 -0700114 Metadata::Filter *filter,
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700115 status_t *status)
116{
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700117 int32_t val;
118 if (p.readInt32(&val) != OK)
Nicolas Cataniab2c69392009-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 Catania4df8b2c2009-07-10 13:53:06 -0700125 if( val > kMaxFilterSize || val < 0)
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700126 {
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700127 LOGE("Invalid filter len %d", val);
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700128 *status = BAD_VALUE;
129 return false;
130 }
131
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700132 const size_t num = val;
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700133
134 filter->clear();
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700135 filter->setCapacity(num);
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700136
nikobc726922009-07-20 15:07:26 -0700137 size_t size = num * sizeof(Metadata::Type);
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700138
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700139
140 if (p.dataAvail() < size)
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700141 {
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700142 LOGE("Filter too short expected %d but got %d", size, p.dataAvail());
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700143 *status = NOT_ENOUGH_DATA;
144 return false;
145 }
146
nikobc726922009-07-20 15:07:26 -0700147 const Metadata::Type *data =
148 static_cast<const Metadata::Type*>(p.readInplace(size));
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700149
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700150 if (NULL == data)
Nicolas Cataniab2c69392009-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 Catania4df8b2c2009-07-10 13:53:06 -0700160 for (size_t i = 0; i < num; ++i)
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700161 {
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700162 filter->add(*data);
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700163 ++data;
164 }
165 *status = OK;
166 return true;
167}
168
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700169// @param filter Of metadata type.
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700170// @param val To be searched.
171// @return true if a match was found.
nikobc726922009-07-20 15:07:26 -0700172bool findMetadata(const Metadata::Filter& filter, const int32_t val)
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700173{
174 // Deal with empty and ANY right away
175 if (filter.isEmpty()) return false;
nikobc726922009-07-20 15:07:26 -0700176 if (filter[0] == Metadata::kAny) return true;
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700177
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700178 return filter.indexOf(val) >= 0;
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700179}
180
181} // anonymous namespace
182
183
The Android Open Source Project9066cfe2009-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
Jianhong Jiang999f1ae2009-09-29 23:12:39 -0700205/* static */ const uint32_t MediaPlayerService::AudioOutput::kAudioVideoDelayMs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800206/* static */ int MediaPlayerService::AudioOutput::mMinBufferCount = 4;
207/* static */ bool MediaPlayerService::AudioOutput::mIsOnEmulator = false;
208
209void MediaPlayerService::instantiate() {
210 defaultServiceManager()->addService(
211 String16("media.player"), new MediaPlayerService());
212}
213
214MediaPlayerService::MediaPlayerService()
215{
216 LOGV("MediaPlayerService created");
217 mNextConnId = 1;
218}
219
220MediaPlayerService::~MediaPlayerService()
221{
222 LOGV("MediaPlayerService destroyed");
223}
224
225sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(pid_t pid)
226{
Jean-Baptiste Queru680f8c72009-03-21 11:40:18 -0700227#ifndef NO_OPENCORE
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800228 sp<MediaRecorderClient> recorder = new MediaRecorderClient(pid);
Jean-Baptiste Queru680f8c72009-03-21 11:40:18 -0700229#else
230 sp<MediaRecorderClient> recorder = NULL;
231#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800232 LOGV("Create new media recorder client from pid %d", pid);
233 return recorder;
234}
235
236sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever(pid_t pid)
237{
238 sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
239 LOGV("Create new media retriever from pid %d", pid);
240 return retriever;
241}
242
243sp<IMediaPlayer> MediaPlayerService::create(pid_t pid, const sp<IMediaPlayerClient>& client, const char* url)
244{
245 int32_t connId = android_atomic_inc(&mNextConnId);
246 sp<Client> c = new Client(this, pid, connId, client);
247 LOGV("Create new client(%d) from pid %d, url=%s, connId=%d", connId, pid, url, connId);
248 if (NO_ERROR != c->setDataSource(url))
249 {
250 c.clear();
251 return c;
252 }
253 wp<Client> w = c;
254 Mutex::Autolock lock(mLock);
255 mClients.add(w);
256 return c;
257}
258
259sp<IMediaPlayer> MediaPlayerService::create(pid_t pid, const sp<IMediaPlayerClient>& client,
260 int fd, int64_t offset, int64_t length)
261{
262 int32_t connId = android_atomic_inc(&mNextConnId);
263 sp<Client> c = new Client(this, pid, connId, client);
264 LOGV("Create new client(%d) from pid %d, fd=%d, offset=%lld, length=%lld",
265 connId, pid, fd, offset, length);
266 if (NO_ERROR != c->setDataSource(fd, offset, length)) {
267 c.clear();
268 } else {
269 wp<Client> w = c;
270 Mutex::Autolock lock(mLock);
271 mClients.add(w);
272 }
273 ::close(fd);
274 return c;
275}
276
Andreas Huber784202e2009-10-15 13:46:54 -0700277sp<IOMX> MediaPlayerService::getOMX() {
278 Mutex::Autolock autoLock(mLock);
279
280 if (mOMX.get() == NULL) {
281 mOMX = new OMX;
282 }
283
284 return mOMX;
Andreas Hubere46b7be2009-07-14 16:56:47 -0700285}
286
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800287status_t MediaPlayerService::AudioCache::dump(int fd, const Vector<String16>& args) const
288{
289 const size_t SIZE = 256;
290 char buffer[SIZE];
291 String8 result;
292
293 result.append(" AudioCache\n");
294 if (mHeap != 0) {
295 snprintf(buffer, 255, " heap base(%p), size(%d), flags(%d), device(%s)\n",
296 mHeap->getBase(), mHeap->getSize(), mHeap->getFlags(), mHeap->getDevice());
297 result.append(buffer);
298 }
299 snprintf(buffer, 255, " msec per frame(%f), channel count(%d), format(%d), frame count(%ld)\n",
300 mMsecsPerFrame, mChannelCount, mFormat, mFrameCount);
301 result.append(buffer);
302 snprintf(buffer, 255, " sample rate(%d), size(%d), error(%d), command complete(%s)\n",
303 mSampleRate, mSize, mError, mCommandComplete?"true":"false");
304 result.append(buffer);
305 ::write(fd, result.string(), result.size());
306 return NO_ERROR;
307}
308
309status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
310{
311 const size_t SIZE = 256;
312 char buffer[SIZE];
313 String8 result;
314
315 result.append(" AudioOutput\n");
316 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n",
317 mStreamType, mLeftVolume, mRightVolume);
318 result.append(buffer);
319 snprintf(buffer, 255, " msec per frame(%f), latency (%d)\n",
320 mMsecsPerFrame, mLatency);
321 result.append(buffer);
322 ::write(fd, result.string(), result.size());
323 if (mTrack != 0) {
324 mTrack->dump(fd, args);
325 }
326 return NO_ERROR;
327}
328
329status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args) const
330{
331 const size_t SIZE = 256;
332 char buffer[SIZE];
333 String8 result;
334 result.append(" Client\n");
335 snprintf(buffer, 255, " pid(%d), connId(%d), status(%d), looping(%s)\n",
336 mPid, mConnId, mStatus, mLoop?"true": "false");
337 result.append(buffer);
338 write(fd, result.string(), result.size());
339 if (mAudioOutput != 0) {
340 mAudioOutput->dump(fd, args);
341 }
342 write(fd, "\n", 1);
343 return NO_ERROR;
344}
345
346static int myTid() {
347#ifdef HAVE_GETTID
348 return gettid();
349#else
350 return getpid();
351#endif
352}
353
354#if defined(__arm__)
355extern "C" void get_malloc_leak_info(uint8_t** info, size_t* overallSize,
356 size_t* infoSize, size_t* totalMemory, size_t* backtraceSize);
357extern "C" void free_malloc_leak_info(uint8_t* info);
358
359void memStatus(int fd, const Vector<String16>& args)
360{
361 const size_t SIZE = 256;
362 char buffer[SIZE];
363 String8 result;
364
365 typedef struct {
366 size_t size;
367 size_t dups;
368 intptr_t * backtrace;
369 } AllocEntry;
370
371 uint8_t *info = NULL;
372 size_t overallSize = 0;
373 size_t infoSize = 0;
374 size_t totalMemory = 0;
375 size_t backtraceSize = 0;
376
377 get_malloc_leak_info(&info, &overallSize, &infoSize, &totalMemory, &backtraceSize);
378 if (info) {
379 uint8_t *ptr = info;
380 size_t count = overallSize / infoSize;
381
382 snprintf(buffer, SIZE, " Allocation count %i\n", count);
383 result.append(buffer);
384
385 AllocEntry * entries = new AllocEntry[count];
386
387 for (size_t i = 0; i < count; i++) {
388 // Each entry should be size_t, size_t, intptr_t[backtraceSize]
389 AllocEntry *e = &entries[i];
390
391 e->size = *reinterpret_cast<size_t *>(ptr);
392 ptr += sizeof(size_t);
393
394 e->dups = *reinterpret_cast<size_t *>(ptr);
395 ptr += sizeof(size_t);
396
397 e->backtrace = reinterpret_cast<intptr_t *>(ptr);
398 ptr += sizeof(intptr_t) * backtraceSize;
399 }
400
401 // Now we need to sort the entries. They come sorted by size but
402 // not by stack trace which causes problems using diff.
403 bool moved;
404 do {
405 moved = false;
406 for (size_t i = 0; i < (count - 1); i++) {
407 AllocEntry *e1 = &entries[i];
408 AllocEntry *e2 = &entries[i+1];
409
410 bool swap = e1->size < e2->size;
411 if (e1->size == e2->size) {
412 for(size_t j = 0; j < backtraceSize; j++) {
413 if (e1->backtrace[j] == e2->backtrace[j]) {
414 continue;
415 }
416 swap = e1->backtrace[j] < e2->backtrace[j];
417 break;
418 }
419 }
420 if (swap) {
421 AllocEntry t = entries[i];
422 entries[i] = entries[i+1];
423 entries[i+1] = t;
424 moved = true;
425 }
426 }
427 } while (moved);
428
429 for (size_t i = 0; i < count; i++) {
430 AllocEntry *e = &entries[i];
431
432 snprintf(buffer, SIZE, "size %8i, dup %4i", e->size, e->dups);
433 result.append(buffer);
434 for (size_t ct = 0; (ct < backtraceSize) && e->backtrace[ct]; ct++) {
435 if (ct) {
436 result.append(", ");
437 }
438 snprintf(buffer, SIZE, "0x%08x", e->backtrace[ct]);
439 result.append(buffer);
440 }
441 result.append("\n");
442 }
443
444 delete[] entries;
445 free_malloc_leak_info(info);
446 }
447
448 write(fd, result.string(), result.size());
449}
450#endif
451
452status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
453{
454 const size_t SIZE = 256;
455 char buffer[SIZE];
456 String8 result;
457 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
458 snprintf(buffer, SIZE, "Permission Denial: "
459 "can't dump MediaPlayerService from pid=%d, uid=%d\n",
460 IPCThreadState::self()->getCallingPid(),
461 IPCThreadState::self()->getCallingUid());
462 result.append(buffer);
463 } else {
464 Mutex::Autolock lock(mLock);
465 for (int i = 0, n = mClients.size(); i < n; ++i) {
466 sp<Client> c = mClients[i].promote();
467 if (c != 0) c->dump(fd, args);
468 }
469 result.append(" Files opened and/or mapped:\n");
470 snprintf(buffer, SIZE, "/proc/%d/maps", myTid());
471 FILE *f = fopen(buffer, "r");
472 if (f) {
473 while (!feof(f)) {
474 fgets(buffer, SIZE, f);
475 if (strstr(buffer, " /sdcard/") ||
476 strstr(buffer, " /system/sounds/") ||
477 strstr(buffer, " /system/media/")) {
478 result.append(" ");
479 result.append(buffer);
480 }
481 }
482 fclose(f);
483 } else {
484 result.append("couldn't open ");
485 result.append(buffer);
486 result.append("\n");
487 }
488
489 snprintf(buffer, SIZE, "/proc/%d/fd", myTid());
490 DIR *d = opendir(buffer);
491 if (d) {
492 struct dirent *ent;
493 while((ent = readdir(d)) != NULL) {
494 if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
495 snprintf(buffer, SIZE, "/proc/%d/fd/%s", myTid(), ent->d_name);
496 struct stat s;
497 if (lstat(buffer, &s) == 0) {
498 if ((s.st_mode & S_IFMT) == S_IFLNK) {
499 char linkto[256];
500 int len = readlink(buffer, linkto, sizeof(linkto));
501 if(len > 0) {
502 if(len > 255) {
503 linkto[252] = '.';
504 linkto[253] = '.';
505 linkto[254] = '.';
506 linkto[255] = 0;
507 } else {
508 linkto[len] = 0;
509 }
510 if (strstr(linkto, "/sdcard/") == linkto ||
511 strstr(linkto, "/system/sounds/") == linkto ||
512 strstr(linkto, "/system/media/") == linkto) {
513 result.append(" ");
514 result.append(buffer);
515 result.append(" -> ");
516 result.append(linkto);
517 result.append("\n");
518 }
519 }
520 } else {
521 result.append(" unexpected type for ");
522 result.append(buffer);
523 result.append("\n");
524 }
525 }
526 }
527 }
528 closedir(d);
529 } else {
530 result.append("couldn't open ");
531 result.append(buffer);
532 result.append("\n");
533 }
534
535#if defined(__arm__)
536 bool dumpMem = false;
537 for (size_t i = 0; i < args.size(); i++) {
538 if (args[i] == String16("-m")) {
539 dumpMem = true;
540 }
541 }
542 if (dumpMem) {
543 memStatus(fd, args);
544 }
545#endif
546 }
547 write(fd, result.string(), result.size());
548 return NO_ERROR;
549}
550
551void MediaPlayerService::removeClient(wp<Client> client)
552{
553 Mutex::Autolock lock(mLock);
554 mClients.remove(client);
555}
556
557MediaPlayerService::Client::Client(const sp<MediaPlayerService>& service, pid_t pid,
558 int32_t connId, const sp<IMediaPlayerClient>& client)
559{
560 LOGV("Client(%d) constructor", connId);
561 mPid = pid;
562 mConnId = connId;
563 mService = service;
564 mClient = client;
565 mLoop = false;
566 mStatus = NO_INIT;
567#if CALLBACK_ANTAGONIZER
568 LOGD("create Antagonizer");
569 mAntagonizer = new Antagonizer(notify, this);
570#endif
571}
572
573MediaPlayerService::Client::~Client()
574{
575 LOGV("Client(%d) destructor pid = %d", mConnId, mPid);
576 mAudioOutput.clear();
577 wp<Client> client(this);
578 disconnect();
579 mService->removeClient(client);
580}
581
582void MediaPlayerService::Client::disconnect()
583{
584 LOGV("disconnect(%d) from pid %d", mConnId, mPid);
585 // grab local reference and clear main reference to prevent future
586 // access to object
587 sp<MediaPlayerBase> p;
588 {
589 Mutex::Autolock l(mLock);
590 p = mPlayer;
591 }
Dave Sparkscb9a44e2009-03-24 17:57:12 -0700592 mClient.clear();
Andreas Hubere46b7be2009-07-14 16:56:47 -0700593
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800594 mPlayer.clear();
595
596 // clear the notification to prevent callbacks to dead client
597 // and reset the player. We assume the player will serialize
598 // access to itself if necessary.
599 if (p != 0) {
600 p->setNotifyCallback(0, 0);
601#if CALLBACK_ANTAGONIZER
602 LOGD("kill Antagonizer");
603 mAntagonizer->kill();
604#endif
605 p->reset();
606 }
607
608 IPCThreadState::self()->flushCommands();
609}
610
Andreas Huber0d596d42009-08-07 09:30:32 -0700611static player_type getDefaultPlayerType() {
Andreas Huber2aa39c42009-09-11 09:54:52 -0700612#if BUILD_WITH_FULL_STAGEFRIGHT
Andreas Huber0d596d42009-08-07 09:30:32 -0700613 char value[PROPERTY_VALUE_MAX];
614 if (property_get("media.stagefright.enable-player", value, NULL)
615 && (!strcmp(value, "1") || !strcasecmp(value, "true"))) {
616 return STAGEFRIGHT_PLAYER;
617 }
Andreas Huber2aa39c42009-09-11 09:54:52 -0700618#endif
Andreas Huber0d596d42009-08-07 09:30:32 -0700619
620 return PV_PLAYER;
621}
622
James Dong392ff3b2009-09-06 14:29:45 -0700623player_type getPlayerType(int fd, int64_t offset, int64_t length)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800624{
625 char buf[20];
626 lseek(fd, offset, SEEK_SET);
627 read(fd, buf, sizeof(buf));
628 lseek(fd, offset, SEEK_SET);
629
630 long ident = *((long*)buf);
631
632 // Ogg vorbis?
633 if (ident == 0x5367674f) // 'OggS'
634 return VORBIS_PLAYER;
635
636 // Some kind of MIDI?
637 EAS_DATA_HANDLE easdata;
638 if (EAS_Init(&easdata) == EAS_SUCCESS) {
639 EAS_FILE locator;
640 locator.path = NULL;
641 locator.fd = fd;
642 locator.offset = offset;
643 locator.length = length;
644 EAS_HANDLE eashandle;
645 if (EAS_OpenFile(easdata, &locator, &eashandle) == EAS_SUCCESS) {
646 EAS_CloseFile(easdata, eashandle);
647 EAS_Shutdown(easdata);
648 return SONIVOX_PLAYER;
649 }
650 EAS_Shutdown(easdata);
651 }
652
Andreas Huber0d596d42009-08-07 09:30:32 -0700653 return getDefaultPlayerType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800654}
655
James Dong392ff3b2009-09-06 14:29:45 -0700656player_type getPlayerType(const char* url)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800657{
Nicolas Catania8f5fcab2009-07-13 14:37:49 -0700658 if (TestPlayerStub::canBeUsed(url)) {
659 return TEST_PLAYER;
660 }
661
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800662 // use MidiFile for MIDI extensions
663 int lenURL = strlen(url);
664 for (int i = 0; i < NELEM(FILE_EXTS); ++i) {
665 int len = strlen(FILE_EXTS[i].extension);
666 int start = lenURL - len;
667 if (start > 0) {
668 if (!strncmp(url + start, FILE_EXTS[i].extension, len)) {
669 return FILE_EXTS[i].playertype;
670 }
671 }
672 }
673
Andreas Huber0d596d42009-08-07 09:30:32 -0700674 return getDefaultPlayerType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800675}
676
677static sp<MediaPlayerBase> createPlayer(player_type playerType, void* cookie,
678 notify_callback_f notifyFunc)
679{
680 sp<MediaPlayerBase> p;
681 switch (playerType) {
Jean-Baptiste Queru680f8c72009-03-21 11:40:18 -0700682#ifndef NO_OPENCORE
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800683 case PV_PLAYER:
684 LOGV(" create PVPlayer");
685 p = new PVPlayer();
686 break;
Jean-Baptiste Queru680f8c72009-03-21 11:40:18 -0700687#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800688 case SONIVOX_PLAYER:
689 LOGV(" create MidiFile");
690 p = new MidiFile();
691 break;
692 case VORBIS_PLAYER:
693 LOGV(" create VorbisPlayer");
694 p = new VorbisPlayer();
695 break;
Andreas Huber2aa39c42009-09-11 09:54:52 -0700696#if BUILD_WITH_FULL_STAGEFRIGHT
Andreas Hubere46b7be2009-07-14 16:56:47 -0700697 case STAGEFRIGHT_PLAYER:
698 LOGV(" create StagefrightPlayer");
699 p = new StagefrightPlayer;
700 break;
Andreas Huber2aa39c42009-09-11 09:54:52 -0700701#endif
Nicolas Catania8f5fcab2009-07-13 14:37:49 -0700702 case TEST_PLAYER:
703 LOGV("Create Test Player stub");
704 p = new TestPlayerStub();
705 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800706 }
707 if (p != NULL) {
708 if (p->initCheck() == NO_ERROR) {
709 p->setNotifyCallback(cookie, notifyFunc);
710 } else {
711 p.clear();
712 }
713 }
714 if (p == NULL) {
715 LOGE("Failed to create player object");
716 }
717 return p;
718}
719
720sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
721{
722 // determine if we have the right player type
723 sp<MediaPlayerBase> p = mPlayer;
724 if ((p != NULL) && (p->playerType() != playerType)) {
725 LOGV("delete player");
726 p.clear();
727 }
728 if (p == NULL) {
729 p = android::createPlayer(playerType, this, notify);
730 }
731 return p;
732}
733
734status_t MediaPlayerService::Client::setDataSource(const char *url)
735{
736 LOGV("setDataSource(%s)", url);
737 if (url == NULL)
738 return UNKNOWN_ERROR;
739
740 if (strncmp(url, "content://", 10) == 0) {
741 // get a filedescriptor for the content Uri and
742 // pass it to the setDataSource(fd) method
743
744 String16 url16(url);
745 int fd = android::openContentProviderFile(url16);
746 if (fd < 0)
747 {
748 LOGE("Couldn't open fd for %s", url);
749 return UNKNOWN_ERROR;
750 }
751 setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
752 close(fd);
753 return mStatus;
754 } else {
755 player_type playerType = getPlayerType(url);
756 LOGV("player type = %d", playerType);
757
758 // create the right type of player
759 sp<MediaPlayerBase> p = createPlayer(playerType);
760 if (p == NULL) return NO_INIT;
761
762 if (!p->hardwareOutput()) {
763 mAudioOutput = new AudioOutput();
764 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
765 }
766
767 // now set data source
768 LOGV(" setDataSource");
769 mStatus = p->setDataSource(url);
Nicolas Catania8f5fcab2009-07-13 14:37:49 -0700770 if (mStatus == NO_ERROR) {
771 mPlayer = p;
772 } else {
773 LOGE(" error: %d", mStatus);
774 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800775 return mStatus;
776 }
777}
778
779status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
780{
781 LOGV("setDataSource fd=%d, offset=%lld, length=%lld", fd, offset, length);
782 struct stat sb;
783 int ret = fstat(fd, &sb);
784 if (ret != 0) {
785 LOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
786 return UNKNOWN_ERROR;
787 }
788
789 LOGV("st_dev = %llu", sb.st_dev);
790 LOGV("st_mode = %u", sb.st_mode);
791 LOGV("st_uid = %lu", sb.st_uid);
792 LOGV("st_gid = %lu", sb.st_gid);
793 LOGV("st_size = %llu", sb.st_size);
794
795 if (offset >= sb.st_size) {
796 LOGE("offset error");
797 ::close(fd);
798 return UNKNOWN_ERROR;
799 }
800 if (offset + length > sb.st_size) {
801 length = sb.st_size - offset;
802 LOGV("calculated length = %lld", length);
803 }
804
805 player_type playerType = getPlayerType(fd, offset, length);
806 LOGV("player type = %d", playerType);
807
808 // create the right type of player
809 sp<MediaPlayerBase> p = createPlayer(playerType);
810 if (p == NULL) return NO_INIT;
811
812 if (!p->hardwareOutput()) {
813 mAudioOutput = new AudioOutput();
814 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
815 }
816
817 // now set data source
818 mStatus = p->setDataSource(fd, offset, length);
819 if (mStatus == NO_ERROR) mPlayer = p;
820 return mStatus;
821}
822
823status_t MediaPlayerService::Client::setVideoSurface(const sp<ISurface>& surface)
824{
825 LOGV("[%d] setVideoSurface(%p)", mConnId, surface.get());
826 sp<MediaPlayerBase> p = getPlayer();
827 if (p == 0) return UNKNOWN_ERROR;
828 return p->setVideoSurface(surface);
829}
830
Nicolas Catania20cb94e2009-05-12 23:25:55 -0700831status_t MediaPlayerService::Client::invoke(const Parcel& request,
832 Parcel *reply)
833{
834 sp<MediaPlayerBase> p = getPlayer();
835 if (p == NULL) return UNKNOWN_ERROR;
836 return p->invoke(request, reply);
837}
838
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700839// This call doesn't need to access the native player.
840status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
841{
842 status_t status;
nikobc726922009-07-20 15:07:26 -0700843 media::Metadata::Filter allow, drop;
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700844
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700845 if (unmarshallFilter(filter, &allow, &status) &&
846 unmarshallFilter(filter, &drop, &status)) {
847 Mutex::Autolock lock(mLock);
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700848
849 mMetadataAllow = allow;
850 mMetadataDrop = drop;
851 }
852 return status;
853}
854
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700855status_t MediaPlayerService::Client::getMetadata(
856 bool update_only, bool apply_filter, Parcel *reply)
Nicolas Catania5d55c712009-07-09 09:21:33 -0700857{
nikobc726922009-07-20 15:07:26 -0700858 sp<MediaPlayerBase> player = getPlayer();
859 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700860
niko89948372009-07-16 16:39:53 -0700861 status_t status;
862 // Placeholder for the return code, updated by the caller.
863 reply->writeInt32(-1);
864
nikobc726922009-07-20 15:07:26 -0700865 media::Metadata::Filter ids;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700866
867 // We don't block notifications while we fetch the data. We clear
868 // mMetadataUpdated first so we don't lose notifications happening
869 // during the rest of this call.
870 {
871 Mutex::Autolock lock(mLock);
872 if (update_only) {
niko89948372009-07-16 16:39:53 -0700873 ids = mMetadataUpdated;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700874 }
875 mMetadataUpdated.clear();
876 }
Nicolas Catania5d55c712009-07-09 09:21:33 -0700877
nikobc726922009-07-20 15:07:26 -0700878 media::Metadata metadata(reply);
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700879
nikobc726922009-07-20 15:07:26 -0700880 metadata.appendHeader();
881 status = player->getMetadata(ids, reply);
niko89948372009-07-16 16:39:53 -0700882
883 if (status != OK) {
nikobc726922009-07-20 15:07:26 -0700884 metadata.resetParcel();
niko89948372009-07-16 16:39:53 -0700885 LOGE("getMetadata failed %d", status);
886 return status;
887 }
888
889 // FIXME: Implement filtering on the result. Not critical since
890 // filtering takes place on the update notifications already. This
891 // would be when all the metadata are fetch and a filter is set.
892
niko89948372009-07-16 16:39:53 -0700893 // Everything is fine, update the metadata length.
nikobc726922009-07-20 15:07:26 -0700894 metadata.updateLength();
niko89948372009-07-16 16:39:53 -0700895 return OK;
Nicolas Catania5d55c712009-07-09 09:21:33 -0700896}
897
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800898status_t MediaPlayerService::Client::prepareAsync()
899{
900 LOGV("[%d] prepareAsync", mConnId);
901 sp<MediaPlayerBase> p = getPlayer();
902 if (p == 0) return UNKNOWN_ERROR;
903 status_t ret = p->prepareAsync();
904#if CALLBACK_ANTAGONIZER
905 LOGD("start Antagonizer");
906 if (ret == NO_ERROR) mAntagonizer->start();
907#endif
908 return ret;
909}
910
911status_t MediaPlayerService::Client::start()
912{
913 LOGV("[%d] start", mConnId);
914 sp<MediaPlayerBase> p = getPlayer();
915 if (p == 0) return UNKNOWN_ERROR;
916 p->setLooping(mLoop);
917 return p->start();
918}
919
920status_t MediaPlayerService::Client::stop()
921{
922 LOGV("[%d] stop", mConnId);
923 sp<MediaPlayerBase> p = getPlayer();
924 if (p == 0) return UNKNOWN_ERROR;
925 return p->stop();
926}
927
928status_t MediaPlayerService::Client::pause()
929{
930 LOGV("[%d] pause", mConnId);
931 sp<MediaPlayerBase> p = getPlayer();
932 if (p == 0) return UNKNOWN_ERROR;
933 return p->pause();
934}
935
936status_t MediaPlayerService::Client::isPlaying(bool* state)
937{
938 *state = false;
939 sp<MediaPlayerBase> p = getPlayer();
940 if (p == 0) return UNKNOWN_ERROR;
941 *state = p->isPlaying();
942 LOGV("[%d] isPlaying: %d", mConnId, *state);
943 return NO_ERROR;
944}
945
946status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
947{
948 LOGV("getCurrentPosition");
949 sp<MediaPlayerBase> p = getPlayer();
950 if (p == 0) return UNKNOWN_ERROR;
951 status_t ret = p->getCurrentPosition(msec);
952 if (ret == NO_ERROR) {
953 LOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
954 } else {
955 LOGE("getCurrentPosition returned %d", ret);
956 }
957 return ret;
958}
959
960status_t MediaPlayerService::Client::getDuration(int *msec)
961{
962 LOGV("getDuration");
963 sp<MediaPlayerBase> p = getPlayer();
964 if (p == 0) return UNKNOWN_ERROR;
965 status_t ret = p->getDuration(msec);
966 if (ret == NO_ERROR) {
967 LOGV("[%d] getDuration = %d", mConnId, *msec);
968 } else {
969 LOGE("getDuration returned %d", ret);
970 }
971 return ret;
972}
973
974status_t MediaPlayerService::Client::seekTo(int msec)
975{
976 LOGV("[%d] seekTo(%d)", mConnId, msec);
977 sp<MediaPlayerBase> p = getPlayer();
978 if (p == 0) return UNKNOWN_ERROR;
979 return p->seekTo(msec);
980}
981
982status_t MediaPlayerService::Client::reset()
983{
984 LOGV("[%d] reset", mConnId);
985 sp<MediaPlayerBase> p = getPlayer();
986 if (p == 0) return UNKNOWN_ERROR;
987 return p->reset();
988}
989
990status_t MediaPlayerService::Client::setAudioStreamType(int type)
991{
992 LOGV("[%d] setAudioStreamType(%d)", mConnId, type);
993 // TODO: for hardware output, call player instead
994 Mutex::Autolock l(mLock);
995 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
996 return NO_ERROR;
997}
998
999status_t MediaPlayerService::Client::setLooping(int loop)
1000{
1001 LOGV("[%d] setLooping(%d)", mConnId, loop);
1002 mLoop = loop;
1003 sp<MediaPlayerBase> p = getPlayer();
1004 if (p != 0) return p->setLooping(loop);
1005 return NO_ERROR;
1006}
1007
1008status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1009{
1010 LOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
1011 // TODO: for hardware output, call player instead
1012 Mutex::Autolock l(mLock);
1013 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1014 return NO_ERROR;
1015}
1016
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001017
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001018void MediaPlayerService::Client::notify(void* cookie, int msg, int ext1, int ext2)
1019{
1020 Client* client = static_cast<Client*>(cookie);
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001021
1022 if (MEDIA_INFO == msg &&
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001023 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikobc726922009-07-20 15:07:26 -07001024 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001025
1026 if(client->shouldDropMetadata(metadata_type)) {
1027 return;
1028 }
1029
1030 // Update the list of metadata that have changed. getMetadata
1031 // also access mMetadataUpdated and clears it.
1032 client->addNewMetadataUpdate(metadata_type);
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001033 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001034 LOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
1035 client->mClient->notify(msg, ext1, ext2);
1036}
1037
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001038
nikobc726922009-07-20 15:07:26 -07001039bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001040{
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001041 Mutex::Autolock lock(mLock);
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001042
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001043 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001044 return true;
1045 }
1046
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001047 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001048 return false;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001049 } else {
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001050 return true;
1051 }
1052}
1053
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001054
nikobc726922009-07-20 15:07:26 -07001055void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001056 Mutex::Autolock lock(mLock);
1057 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1058 mMetadataUpdated.add(metadata_type);
1059 }
1060}
1061
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001062#if CALLBACK_ANTAGONIZER
1063const int Antagonizer::interval = 10000; // 10 msecs
1064
1065Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1066 mExit(false), mActive(false), mClient(client), mCb(cb)
1067{
1068 createThread(callbackThread, this);
1069}
1070
1071void Antagonizer::kill()
1072{
1073 Mutex::Autolock _l(mLock);
1074 mActive = false;
1075 mExit = true;
1076 mCondition.wait(mLock);
1077}
1078
1079int Antagonizer::callbackThread(void* user)
1080{
1081 LOGD("Antagonizer started");
1082 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1083 while (!p->mExit) {
1084 if (p->mActive) {
1085 LOGV("send event");
1086 p->mCb(p->mClient, 0, 0, 0);
1087 }
1088 usleep(interval);
1089 }
1090 Mutex::Autolock _l(p->mLock);
1091 p->mCondition.signal();
1092 LOGD("Antagonizer stopped");
1093 return 0;
1094}
1095#endif
1096
1097static size_t kDefaultHeapSize = 1024 * 1024; // 1MB
1098
1099sp<IMemory> MediaPlayerService::decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1100{
1101 LOGV("decode(%s)", url);
1102 sp<MemoryBase> mem;
1103 sp<MediaPlayerBase> player;
1104
1105 // Protect our precious, precious DRMd ringtones by only allowing
1106 // decoding of http, but not filesystem paths or content Uris.
1107 // If the application wants to decode those, it should open a
1108 // filedescriptor for them and use that.
1109 if (url != NULL && strncmp(url, "http://", 7) != 0) {
1110 LOGD("Can't decode %s by path, use filedescriptor instead", url);
1111 return mem;
1112 }
1113
1114 player_type playerType = getPlayerType(url);
1115 LOGV("player type = %d", playerType);
1116
1117 // create the right type of player
1118 sp<AudioCache> cache = new AudioCache(url);
1119 player = android::createPlayer(playerType, cache.get(), cache->notify);
1120 if (player == NULL) goto Exit;
1121 if (player->hardwareOutput()) goto Exit;
1122
1123 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1124
1125 // set data source
1126 if (player->setDataSource(url) != NO_ERROR) goto Exit;
1127
1128 LOGV("prepare");
1129 player->prepareAsync();
1130
1131 LOGV("wait for prepare");
1132 if (cache->wait() != NO_ERROR) goto Exit;
1133
1134 LOGV("start");
1135 player->start();
1136
1137 LOGV("wait for playback complete");
1138 if (cache->wait() != NO_ERROR) goto Exit;
1139
1140 mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1141 *pSampleRate = cache->sampleRate();
1142 *pNumChannels = cache->channelCount();
1143 *pFormat = cache->format();
1144 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1145
1146Exit:
1147 if (player != 0) player->reset();
1148 return mem;
1149}
1150
1151sp<IMemory> MediaPlayerService::decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1152{
1153 LOGV("decode(%d, %lld, %lld)", fd, offset, length);
1154 sp<MemoryBase> mem;
1155 sp<MediaPlayerBase> player;
1156
1157 player_type playerType = getPlayerType(fd, offset, length);
1158 LOGV("player type = %d", playerType);
1159
1160 // create the right type of player
1161 sp<AudioCache> cache = new AudioCache("decode_fd");
1162 player = android::createPlayer(playerType, cache.get(), cache->notify);
1163 if (player == NULL) goto Exit;
1164 if (player->hardwareOutput()) goto Exit;
1165
1166 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1167
1168 // set data source
1169 if (player->setDataSource(fd, offset, length) != NO_ERROR) goto Exit;
1170
1171 LOGV("prepare");
1172 player->prepareAsync();
1173
1174 LOGV("wait for prepare");
1175 if (cache->wait() != NO_ERROR) goto Exit;
1176
1177 LOGV("start");
1178 player->start();
1179
1180 LOGV("wait for playback complete");
1181 if (cache->wait() != NO_ERROR) goto Exit;
1182
1183 mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1184 *pSampleRate = cache->sampleRate();
1185 *pNumChannels = cache->channelCount();
1186 *pFormat = cache->format();
1187 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1188
1189Exit:
1190 if (player != 0) player->reset();
1191 ::close(fd);
1192 return mem;
1193}
1194
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001195/*
1196 * Avert your eyes, ugly hack ahead.
1197 * The following is to support music visualizations.
1198 */
1199
1200static const int NUMVIZBUF = 32;
1201static const int VIZBUFFRAMES = 1024;
1202static const int TOTALBUFTIMEMSEC = NUMVIZBUF * VIZBUFFRAMES * 1000 / 44100;
1203
1204static bool gotMem = false;
1205static sp<MemoryBase> mem[NUMVIZBUF];
1206static uint64_t timeStamp[NUMVIZBUF];
1207static uint64_t lastReadTime;
1208static uint64_t lastWriteTime;
1209static int writeIdx = 0;
1210
1211static void allocVizBufs() {
1212 if (!gotMem) {
1213 for (int i=0;i<NUMVIZBUF;i++) {
1214 sp<MemoryHeapBase> heap = new MemoryHeapBase(VIZBUFFRAMES*2, 0, "snooper");
1215 mem[i] = new MemoryBase(heap, 0, heap->getSize());
1216 timeStamp[i] = 0;
1217 }
1218 gotMem = true;
1219 }
1220}
1221
1222
1223/*
1224 * Get a buffer of audio data that is about to be played.
1225 * We don't synchronize this because in practice the writer
1226 * is ahead of the reader, and even if we did happen to catch
1227 * a buffer while it's being written, it's just a visualization,
1228 * so no harm done.
1229 */
1230static sp<MemoryBase> getVizBuffer() {
1231
1232 allocVizBufs();
1233
1234 lastReadTime = uptimeMillis() + 100; // account for renderer delay (we shouldn't be doing this here)
1235
1236 // if there is no recent buffer (yet), just return empty handed
1237 if (lastWriteTime + TOTALBUFTIMEMSEC < lastReadTime) {
1238 //LOGI("@@@@ no audio data to look at yet");
1239 return NULL;
1240 }
1241
1242 char buf[200];
1243
1244 int closestIdx = -1;
1245 uint32_t closestTime = 0x7ffffff;
1246
1247 for (int i = 0; i < NUMVIZBUF; i++) {
1248 uint64_t tsi = timeStamp[i];
1249 uint64_t diff = tsi > lastReadTime ? tsi - lastReadTime : lastReadTime - tsi;
1250 if (diff < closestTime) {
1251 closestIdx = i;
1252 closestTime = diff;
1253 }
1254 }
1255
1256
1257 if (closestIdx >= 0) {
1258 //LOGI("@@@ return buffer %d, %d/%d", closestIdx, uint32_t(lastReadTime), uint32_t(timeStamp[closestIdx]));
1259 return mem[closestIdx];
1260 }
1261
1262 // we won't get here, since we either bailed out early, or got a buffer
1263 LOGD("Didn't expect to be here");
1264 return NULL;
1265}
1266
1267static void storeVizBuf(const void *data, int len, uint64_t time) {
1268 // Copy the data in to the visualizer buffer
1269 // Assume a 16 bit stereo source for now.
1270 short *viz = (short*)mem[writeIdx]->pointer();
1271 short *src = (short*)data;
1272 for (int i = 0; i < VIZBUFFRAMES; i++) {
1273 // Degrade quality by mixing to mono and clearing the lowest 3 bits.
1274 // This should still be good enough for a visualization
1275 *viz++ = ((int(src[0]) + int(src[1])) >> 1) & ~0x7;
1276 src += 2;
1277 }
1278 timeStamp[writeIdx++] = time;
1279 if (writeIdx >= NUMVIZBUF) {
1280 writeIdx = 0;
1281 }
1282}
1283
1284static void makeVizBuffers(const char *data, int len, uint64_t time) {
1285
1286 allocVizBufs();
1287
1288 uint64_t startTime = time;
1289 const int frameSize = 4; // 16 bit stereo sample is 4 bytes
1290 while (len >= VIZBUFFRAMES * frameSize) {
1291 storeVizBuf(data, len, time);
1292 data += VIZBUFFRAMES * frameSize;
1293 len -= VIZBUFFRAMES * frameSize;
1294 time += 1000 * VIZBUFFRAMES / 44100;
1295 }
1296 //LOGI("@@@ stored buffers from %d to %d", uint32_t(startTime), uint32_t(time));
1297}
1298
1299sp<IMemory> MediaPlayerService::snoop()
1300{
1301 sp<MemoryBase> mem = getVizBuffer();
1302 return mem;
1303}
1304
1305
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001306#undef LOG_TAG
1307#define LOG_TAG "AudioSink"
1308MediaPlayerService::AudioOutput::AudioOutput()
Andreas Hubere46b7be2009-07-14 16:56:47 -07001309 : mCallback(NULL),
1310 mCallbackCookie(NULL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001311 mTrack = 0;
1312 mStreamType = AudioSystem::MUSIC;
1313 mLeftVolume = 1.0;
1314 mRightVolume = 1.0;
1315 mLatency = 0;
1316 mMsecsPerFrame = 0;
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001317 mNumFramesWritten = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001318 setMinBufferCount();
1319}
1320
1321MediaPlayerService::AudioOutput::~AudioOutput()
1322{
1323 close();
1324}
1325
1326void MediaPlayerService::AudioOutput::setMinBufferCount()
1327{
1328 char value[PROPERTY_VALUE_MAX];
1329 if (property_get("ro.kernel.qemu", value, 0)) {
1330 mIsOnEmulator = true;
1331 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1332 }
1333}
1334
1335bool MediaPlayerService::AudioOutput::isOnEmulator()
1336{
1337 setMinBufferCount();
1338 return mIsOnEmulator;
1339}
1340
1341int MediaPlayerService::AudioOutput::getMinBufferCount()
1342{
1343 setMinBufferCount();
1344 return mMinBufferCount;
1345}
1346
1347ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1348{
1349 if (mTrack == 0) return NO_INIT;
1350 return mTrack->frameCount() * frameSize();
1351}
1352
1353ssize_t MediaPlayerService::AudioOutput::frameCount() const
1354{
1355 if (mTrack == 0) return NO_INIT;
1356 return mTrack->frameCount();
1357}
1358
1359ssize_t MediaPlayerService::AudioOutput::channelCount() const
1360{
1361 if (mTrack == 0) return NO_INIT;
1362 return mTrack->channelCount();
1363}
1364
1365ssize_t MediaPlayerService::AudioOutput::frameSize() const
1366{
1367 if (mTrack == 0) return NO_INIT;
1368 return mTrack->frameSize();
1369}
1370
1371uint32_t MediaPlayerService::AudioOutput::latency () const
1372{
1373 return mLatency;
1374}
1375
1376float MediaPlayerService::AudioOutput::msecsPerFrame() const
1377{
1378 return mMsecsPerFrame;
1379}
1380
Andreas Hubere46b7be2009-07-14 16:56:47 -07001381status_t MediaPlayerService::AudioOutput::open(
1382 uint32_t sampleRate, int channelCount, int format, int bufferCount,
1383 AudioCallback cb, void *cookie)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001384{
Andreas Hubere46b7be2009-07-14 16:56:47 -07001385 mCallback = cb;
1386 mCallbackCookie = cookie;
1387
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001388 // Check argument "bufferCount" against the mininum buffer count
1389 if (bufferCount < mMinBufferCount) {
1390 LOGD("bufferCount (%d) is too small and increased to %d", bufferCount, mMinBufferCount);
1391 bufferCount = mMinBufferCount;
1392
1393 }
1394 LOGV("open(%u, %d, %d, %d)", sampleRate, channelCount, format, bufferCount);
1395 if (mTrack) close();
1396 int afSampleRate;
1397 int afFrameCount;
1398 int frameCount;
1399
1400 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1401 return NO_INIT;
1402 }
1403 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1404 return NO_INIT;
1405 }
1406
1407 frameCount = (sampleRate*afFrameCount*bufferCount)/afSampleRate;
Andreas Hubere46b7be2009-07-14 16:56:47 -07001408
1409 AudioTrack *t;
1410 if (mCallback != NULL) {
1411 t = new AudioTrack(
Eric Laurenta553c252009-07-17 12:17:14 -07001412 mStreamType,
1413 sampleRate,
1414 format,
1415 (channelCount == 2) ? AudioSystem::CHANNEL_OUT_STEREO : AudioSystem::CHANNEL_OUT_MONO,
1416 frameCount,
1417 0 /* flags */,
1418 CallbackWrapper,
1419 this);
Andreas Hubere46b7be2009-07-14 16:56:47 -07001420 } else {
1421 t = new AudioTrack(
Eric Laurenta553c252009-07-17 12:17:14 -07001422 mStreamType,
1423 sampleRate,
1424 format,
1425 (channelCount == 2) ? AudioSystem::CHANNEL_OUT_STEREO : AudioSystem::CHANNEL_OUT_MONO,
1426 frameCount);
Andreas Hubere46b7be2009-07-14 16:56:47 -07001427 }
1428
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001429 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1430 LOGE("Unable to create audio track");
1431 delete t;
1432 return NO_INIT;
1433 }
1434
1435 LOGV("setVolume");
1436 t->setVolume(mLeftVolume, mRightVolume);
1437 mMsecsPerFrame = 1.e3 / (float) sampleRate;
1438 mLatency = t->latency() + kAudioVideoDelayMs;
1439 mTrack = t;
1440 return NO_ERROR;
1441}
1442
1443void MediaPlayerService::AudioOutput::start()
1444{
1445 LOGV("start");
1446 if (mTrack) {
1447 mTrack->setVolume(mLeftVolume, mRightVolume);
1448 mTrack->start();
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001449 mTrack->getPosition(&mNumFramesWritten);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001450 }
1451}
1452
1453ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size)
1454{
Andreas Hubere46b7be2009-07-14 16:56:47 -07001455 LOG_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
1456
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001457 //LOGV("write(%p, %u)", buffer, size);
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001458 if (mTrack) {
1459 // Only make visualization buffers if anyone recently requested visualization data
1460 uint64_t now = uptimeMillis();
1461 if (lastReadTime + TOTALBUFTIMEMSEC >= now) {
1462 // Based on the current play counter, the number of frames written and
1463 // the current real time we can calculate the approximate real start
1464 // time of the buffer we're about to write.
1465 uint32_t pos;
1466 mTrack->getPosition(&pos);
1467
1468 // we're writing ahead by this many frames:
1469 int ahead = mNumFramesWritten - pos;
1470 //LOGI("@@@ written: %d, playpos: %d, latency: %d", mNumFramesWritten, pos, mTrack->latency());
1471 // which is this many milliseconds, assuming 44100 Hz:
1472 ahead /= 44;
1473
1474 makeVizBuffers((const char*)buffer, size, now + ahead + mTrack->latency());
1475 lastWriteTime = now;
1476 }
1477 ssize_t ret = mTrack->write(buffer, size);
1478 mNumFramesWritten += ret / 4; // assume 16 bit stereo
1479 return ret;
1480 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001481 return NO_INIT;
1482}
1483
1484void MediaPlayerService::AudioOutput::stop()
1485{
1486 LOGV("stop");
1487 if (mTrack) mTrack->stop();
Marco Nelissenc39d2e32009-09-20 10:42:13 -07001488 lastWriteTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001489}
1490
1491void MediaPlayerService::AudioOutput::flush()
1492{
1493 LOGV("flush");
1494 if (mTrack) mTrack->flush();
1495}
1496
1497void MediaPlayerService::AudioOutput::pause()
1498{
1499 LOGV("pause");
1500 if (mTrack) mTrack->pause();
1501}
1502
1503void MediaPlayerService::AudioOutput::close()
1504{
1505 LOGV("close");
1506 delete mTrack;
1507 mTrack = 0;
1508}
1509
1510void MediaPlayerService::AudioOutput::setVolume(float left, float right)
1511{
1512 LOGV("setVolume(%f, %f)", left, right);
1513 mLeftVolume = left;
1514 mRightVolume = right;
1515 if (mTrack) {
1516 mTrack->setVolume(left, right);
1517 }
1518}
1519
Andreas Hubere46b7be2009-07-14 16:56:47 -07001520// static
1521void MediaPlayerService::AudioOutput::CallbackWrapper(
1522 int event, void *cookie, void *info) {
1523 if (event != AudioTrack::EVENT_MORE_DATA) {
1524 return;
1525 }
1526
1527 AudioOutput *me = (AudioOutput *)cookie;
1528 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
1529
1530 (*me->mCallback)(
1531 me, buffer->raw, buffer->size, me->mCallbackCookie);
1532}
1533
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001534#undef LOG_TAG
1535#define LOG_TAG "AudioCache"
1536MediaPlayerService::AudioCache::AudioCache(const char* name) :
1537 mChannelCount(0), mFrameCount(1024), mSampleRate(0), mSize(0),
1538 mError(NO_ERROR), mCommandComplete(false)
1539{
1540 // create ashmem heap
1541 mHeap = new MemoryHeapBase(kDefaultHeapSize, 0, name);
1542}
1543
1544uint32_t MediaPlayerService::AudioCache::latency () const
1545{
1546 return 0;
1547}
1548
1549float MediaPlayerService::AudioCache::msecsPerFrame() const
1550{
1551 return mMsecsPerFrame;
1552}
1553
Andreas Hubere46b7be2009-07-14 16:56:47 -07001554status_t MediaPlayerService::AudioCache::open(
1555 uint32_t sampleRate, int channelCount, int format, int bufferCount,
1556 AudioCallback cb, void *cookie)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001557{
Andreas Hubere46b7be2009-07-14 16:56:47 -07001558 if (cb != NULL) {
1559 return UNKNOWN_ERROR; // TODO: implement this.
1560 }
1561
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001562 LOGV("open(%u, %d, %d, %d)", sampleRate, channelCount, format, bufferCount);
1563 if (mHeap->getHeapID() < 0) return NO_INIT;
1564 mSampleRate = sampleRate;
1565 mChannelCount = (uint16_t)channelCount;
1566 mFormat = (uint16_t)format;
1567 mMsecsPerFrame = 1.e3 / (float) sampleRate;
1568 return NO_ERROR;
1569}
1570
1571ssize_t MediaPlayerService::AudioCache::write(const void* buffer, size_t size)
1572{
1573 LOGV("write(%p, %u)", buffer, size);
1574 if ((buffer == 0) || (size == 0)) return size;
1575
1576 uint8_t* p = static_cast<uint8_t*>(mHeap->getBase());
1577 if (p == NULL) return NO_INIT;
1578 p += mSize;
1579 LOGV("memcpy(%p, %p, %u)", p, buffer, size);
1580 if (mSize + size > mHeap->getSize()) {
1581 LOGE("Heap size overflow! req size: %d, max size: %d", (mSize + size), mHeap->getSize());
1582 size = mHeap->getSize() - mSize;
1583 }
1584 memcpy(p, buffer, size);
1585 mSize += size;
1586 return size;
1587}
1588
1589// call with lock held
1590status_t MediaPlayerService::AudioCache::wait()
1591{
1592 Mutex::Autolock lock(mLock);
1593 if (!mCommandComplete) {
1594 mSignal.wait(mLock);
1595 }
1596 mCommandComplete = false;
1597
1598 if (mError == NO_ERROR) {
1599 LOGV("wait - success");
1600 } else {
1601 LOGV("wait - error");
1602 }
1603 return mError;
1604}
1605
1606void MediaPlayerService::AudioCache::notify(void* cookie, int msg, int ext1, int ext2)
1607{
1608 LOGV("notify(%p, %d, %d, %d)", cookie, msg, ext1, ext2);
1609 AudioCache* p = static_cast<AudioCache*>(cookie);
1610
1611 // ignore buffering messages
1612 if (msg == MEDIA_BUFFERING_UPDATE) return;
1613
1614 // set error condition
1615 if (msg == MEDIA_ERROR) {
1616 LOGE("Error %d, %d occurred", ext1, ext2);
1617 p->mError = ext1;
1618 }
1619
1620 // wake up thread
1621 LOGV("wakeup thread");
1622 p->mCommandComplete = true;
1623 p->mSignal.signal();
1624}
1625
nikobc726922009-07-20 15:07:26 -07001626} // namespace android