blob: a11477a023fd82f105cdf19e4f9705c1a302d999 [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>
44#include <utils/Vector.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080045#include <cutils/properties.h>
46
47#include <media/MediaPlayerInterface.h>
48#include <media/mediarecorder.h>
49#include <media/MediaMetadataRetrieverInterface.h>
nikoa64c8c72009-07-20 15:07:26 -070050#include <media/Metadata.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080051#include <media/AudioTrack.h>
52
53#include "MediaRecorderClient.h"
54#include "MediaPlayerService.h"
55#include "MetadataRetrieverClient.h"
56
57#include "MidiFile.h"
58#include "VorbisPlayer.h"
59#include <media/PVPlayer.h>
Nicolas Catania14d27472009-07-13 14:37:49 -070060#include "TestPlayerStub.h"
Andreas Huber20111aa2009-07-14 16:56:47 -070061#include "StagefrightPlayer.h"
Andreas Huber20111aa2009-07-14 16:56:47 -070062
Andreas Huber20111aa2009-07-14 16:56:47 -070063#include <OMX.h>
Nicolas Catania14d27472009-07-13 14:37:49 -070064
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080065/* desktop Linux needs a little help with gettid() */
66#if defined(HAVE_GETTID) && !defined(HAVE_ANDROID_OS)
67#define __KERNEL__
68# include <linux/unistd.h>
69#ifdef _syscall0
70_syscall0(pid_t,gettid)
71#else
72pid_t gettid() { return syscall(__NR_gettid);}
73#endif
74#undef __KERNEL__
75#endif
76
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070077namespace {
nikoa64c8c72009-07-20 15:07:26 -070078using android::media::Metadata;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070079using android::status_t;
80using android::OK;
81using android::BAD_VALUE;
82using android::NOT_ENOUGH_DATA;
83using android::Parcel;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070084
85// Max number of entries in the filter.
86const int kMaxFilterSize = 64; // I pulled that out of thin air.
87
nikoa64c8c72009-07-20 15:07:26 -070088// FIXME: Move all the metadata related function in the Metadata.cpp
nikod608a812009-07-16 16:39:53 -070089
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -070090
91// Unmarshall a filter from a Parcel.
92// Filter format in a parcel:
93//
94// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
95// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
96// | number of entries (n) |
97// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
98// | metadata type 1 |
99// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
100// | metadata type 2 |
101// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
102// ....
103// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
104// | metadata type n |
105// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
106//
107// @param p Parcel that should start with a filter.
108// @param[out] filter On exit contains the list of metadata type to be
109// filtered.
110// @param[out] status On exit contains the status code to be returned.
111// @return true if the parcel starts with a valid filter.
112bool unmarshallFilter(const Parcel& p,
nikoa64c8c72009-07-20 15:07:26 -0700113 Metadata::Filter *filter,
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700114 status_t *status)
115{
Nicolas Catania48290382009-07-10 13:53:06 -0700116 int32_t val;
117 if (p.readInt32(&val) != OK)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700118 {
119 LOGE("Failed to read filter's length");
120 *status = NOT_ENOUGH_DATA;
121 return false;
122 }
123
Nicolas Catania48290382009-07-10 13:53:06 -0700124 if( val > kMaxFilterSize || val < 0)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700125 {
Nicolas Catania48290382009-07-10 13:53:06 -0700126 LOGE("Invalid filter len %d", val);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700127 *status = BAD_VALUE;
128 return false;
129 }
130
Nicolas Catania48290382009-07-10 13:53:06 -0700131 const size_t num = val;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700132
133 filter->clear();
Nicolas Catania48290382009-07-10 13:53:06 -0700134 filter->setCapacity(num);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700135
nikoa64c8c72009-07-20 15:07:26 -0700136 size_t size = num * sizeof(Metadata::Type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700137
Nicolas Catania48290382009-07-10 13:53:06 -0700138
139 if (p.dataAvail() < size)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700140 {
Nicolas Catania48290382009-07-10 13:53:06 -0700141 LOGE("Filter too short expected %d but got %d", size, p.dataAvail());
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700142 *status = NOT_ENOUGH_DATA;
143 return false;
144 }
145
nikoa64c8c72009-07-20 15:07:26 -0700146 const Metadata::Type *data =
147 static_cast<const Metadata::Type*>(p.readInplace(size));
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700148
Nicolas Catania48290382009-07-10 13:53:06 -0700149 if (NULL == data)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700150 {
151 LOGE("Filter had no data");
152 *status = BAD_VALUE;
153 return false;
154 }
155
156 // TODO: The stl impl of vector would be more efficient here
157 // because it degenerates into a memcpy on pod types. Try to
158 // replace later or use stl::set.
Nicolas Catania48290382009-07-10 13:53:06 -0700159 for (size_t i = 0; i < num; ++i)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700160 {
Nicolas Catania48290382009-07-10 13:53:06 -0700161 filter->add(*data);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700162 ++data;
163 }
164 *status = OK;
165 return true;
166}
167
Nicolas Catania48290382009-07-10 13:53:06 -0700168// @param filter Of metadata type.
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700169// @param val To be searched.
170// @return true if a match was found.
nikoa64c8c72009-07-20 15:07:26 -0700171bool findMetadata(const Metadata::Filter& filter, const int32_t val)
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700172{
173 // Deal with empty and ANY right away
174 if (filter.isEmpty()) return false;
nikoa64c8c72009-07-20 15:07:26 -0700175 if (filter[0] == Metadata::kAny) return true;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700176
Nicolas Catania48290382009-07-10 13:53:06 -0700177 return filter.indexOf(val) >= 0;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700178}
179
180} // anonymous namespace
181
182
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800183namespace android {
184
185// TODO: Temp hack until we can register players
186typedef struct {
187 const char *extension;
188 const player_type playertype;
189} extmap;
190extmap FILE_EXTS [] = {
191 {".mid", SONIVOX_PLAYER},
192 {".midi", SONIVOX_PLAYER},
193 {".smf", SONIVOX_PLAYER},
194 {".xmf", SONIVOX_PLAYER},
195 {".imy", SONIVOX_PLAYER},
196 {".rtttl", SONIVOX_PLAYER},
197 {".rtx", SONIVOX_PLAYER},
198 {".ota", SONIVOX_PLAYER},
199 {".ogg", VORBIS_PLAYER},
200 {".oga", VORBIS_PLAYER},
201};
202
203// TODO: Find real cause of Audio/Video delay in PV framework and remove this workaround
Jianhong Jiangfdf23c72009-09-29 23:12:39 -0700204/* static */ const uint32_t MediaPlayerService::AudioOutput::kAudioVideoDelayMs = 0;
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
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800227 sp<MediaRecorderClient> recorder = new MediaRecorderClient(pid);
Jean-Baptiste Queru6c5b2102009-03-21 11:40:18 -0700228#else
229 sp<MediaRecorderClient> recorder = NULL;
230#endif
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800231 LOGV("Create new media recorder client from pid %d", pid);
232 return recorder;
233}
234
235sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever(pid_t pid)
236{
237 sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
238 LOGV("Create new media retriever from pid %d", pid);
239 return retriever;
240}
241
242sp<IMediaPlayer> MediaPlayerService::create(pid_t pid, const sp<IMediaPlayerClient>& client, const char* url)
243{
244 int32_t connId = android_atomic_inc(&mNextConnId);
245 sp<Client> c = new Client(this, pid, connId, client);
246 LOGV("Create new client(%d) from pid %d, url=%s, connId=%d", connId, pid, url, connId);
247 if (NO_ERROR != c->setDataSource(url))
248 {
249 c.clear();
250 return c;
251 }
252 wp<Client> w = c;
253 Mutex::Autolock lock(mLock);
254 mClients.add(w);
255 return c;
256}
257
258sp<IMediaPlayer> MediaPlayerService::create(pid_t pid, const sp<IMediaPlayerClient>& client,
259 int fd, int64_t offset, int64_t length)
260{
261 int32_t connId = android_atomic_inc(&mNextConnId);
262 sp<Client> c = new Client(this, pid, connId, client);
263 LOGV("Create new client(%d) from pid %d, fd=%d, offset=%lld, length=%lld",
264 connId, pid, fd, offset, length);
265 if (NO_ERROR != c->setDataSource(fd, offset, length)) {
266 c.clear();
267 } else {
268 wp<Client> w = c;
269 Mutex::Autolock lock(mLock);
270 mClients.add(w);
271 }
272 ::close(fd);
273 return c;
274}
275
Andreas Huber20111aa2009-07-14 16:56:47 -0700276sp<IOMX> MediaPlayerService::createOMX() {
Andreas Huber20111aa2009-07-14 16:56:47 -0700277 return new OMX;
Andreas Huber20111aa2009-07-14 16:56:47 -0700278}
279
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800280status_t MediaPlayerService::AudioCache::dump(int fd, const Vector<String16>& args) const
281{
282 const size_t SIZE = 256;
283 char buffer[SIZE];
284 String8 result;
285
286 result.append(" AudioCache\n");
287 if (mHeap != 0) {
288 snprintf(buffer, 255, " heap base(%p), size(%d), flags(%d), device(%s)\n",
289 mHeap->getBase(), mHeap->getSize(), mHeap->getFlags(), mHeap->getDevice());
290 result.append(buffer);
291 }
292 snprintf(buffer, 255, " msec per frame(%f), channel count(%d), format(%d), frame count(%ld)\n",
293 mMsecsPerFrame, mChannelCount, mFormat, mFrameCount);
294 result.append(buffer);
295 snprintf(buffer, 255, " sample rate(%d), size(%d), error(%d), command complete(%s)\n",
296 mSampleRate, mSize, mError, mCommandComplete?"true":"false");
297 result.append(buffer);
298 ::write(fd, result.string(), result.size());
299 return NO_ERROR;
300}
301
302status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
303{
304 const size_t SIZE = 256;
305 char buffer[SIZE];
306 String8 result;
307
308 result.append(" AudioOutput\n");
309 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n",
310 mStreamType, mLeftVolume, mRightVolume);
311 result.append(buffer);
312 snprintf(buffer, 255, " msec per frame(%f), latency (%d)\n",
313 mMsecsPerFrame, mLatency);
314 result.append(buffer);
315 ::write(fd, result.string(), result.size());
316 if (mTrack != 0) {
317 mTrack->dump(fd, args);
318 }
319 return NO_ERROR;
320}
321
322status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args) const
323{
324 const size_t SIZE = 256;
325 char buffer[SIZE];
326 String8 result;
327 result.append(" Client\n");
328 snprintf(buffer, 255, " pid(%d), connId(%d), status(%d), looping(%s)\n",
329 mPid, mConnId, mStatus, mLoop?"true": "false");
330 result.append(buffer);
331 write(fd, result.string(), result.size());
332 if (mAudioOutput != 0) {
333 mAudioOutput->dump(fd, args);
334 }
335 write(fd, "\n", 1);
336 return NO_ERROR;
337}
338
339static int myTid() {
340#ifdef HAVE_GETTID
341 return gettid();
342#else
343 return getpid();
344#endif
345}
346
347#if defined(__arm__)
348extern "C" void get_malloc_leak_info(uint8_t** info, size_t* overallSize,
349 size_t* infoSize, size_t* totalMemory, size_t* backtraceSize);
350extern "C" void free_malloc_leak_info(uint8_t* info);
351
352void memStatus(int fd, const Vector<String16>& args)
353{
354 const size_t SIZE = 256;
355 char buffer[SIZE];
356 String8 result;
357
358 typedef struct {
359 size_t size;
360 size_t dups;
361 intptr_t * backtrace;
362 } AllocEntry;
363
364 uint8_t *info = NULL;
365 size_t overallSize = 0;
366 size_t infoSize = 0;
367 size_t totalMemory = 0;
368 size_t backtraceSize = 0;
369
370 get_malloc_leak_info(&info, &overallSize, &infoSize, &totalMemory, &backtraceSize);
371 if (info) {
372 uint8_t *ptr = info;
373 size_t count = overallSize / infoSize;
374
375 snprintf(buffer, SIZE, " Allocation count %i\n", count);
376 result.append(buffer);
377
378 AllocEntry * entries = new AllocEntry[count];
379
380 for (size_t i = 0; i < count; i++) {
381 // Each entry should be size_t, size_t, intptr_t[backtraceSize]
382 AllocEntry *e = &entries[i];
383
384 e->size = *reinterpret_cast<size_t *>(ptr);
385 ptr += sizeof(size_t);
386
387 e->dups = *reinterpret_cast<size_t *>(ptr);
388 ptr += sizeof(size_t);
389
390 e->backtrace = reinterpret_cast<intptr_t *>(ptr);
391 ptr += sizeof(intptr_t) * backtraceSize;
392 }
393
394 // Now we need to sort the entries. They come sorted by size but
395 // not by stack trace which causes problems using diff.
396 bool moved;
397 do {
398 moved = false;
399 for (size_t i = 0; i < (count - 1); i++) {
400 AllocEntry *e1 = &entries[i];
401 AllocEntry *e2 = &entries[i+1];
402
403 bool swap = e1->size < e2->size;
404 if (e1->size == e2->size) {
405 for(size_t j = 0; j < backtraceSize; j++) {
406 if (e1->backtrace[j] == e2->backtrace[j]) {
407 continue;
408 }
409 swap = e1->backtrace[j] < e2->backtrace[j];
410 break;
411 }
412 }
413 if (swap) {
414 AllocEntry t = entries[i];
415 entries[i] = entries[i+1];
416 entries[i+1] = t;
417 moved = true;
418 }
419 }
420 } while (moved);
421
422 for (size_t i = 0; i < count; i++) {
423 AllocEntry *e = &entries[i];
424
425 snprintf(buffer, SIZE, "size %8i, dup %4i", e->size, e->dups);
426 result.append(buffer);
427 for (size_t ct = 0; (ct < backtraceSize) && e->backtrace[ct]; ct++) {
428 if (ct) {
429 result.append(", ");
430 }
431 snprintf(buffer, SIZE, "0x%08x", e->backtrace[ct]);
432 result.append(buffer);
433 }
434 result.append("\n");
435 }
436
437 delete[] entries;
438 free_malloc_leak_info(info);
439 }
440
441 write(fd, result.string(), result.size());
442}
443#endif
444
445status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
446{
447 const size_t SIZE = 256;
448 char buffer[SIZE];
449 String8 result;
450 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
451 snprintf(buffer, SIZE, "Permission Denial: "
452 "can't dump MediaPlayerService from pid=%d, uid=%d\n",
453 IPCThreadState::self()->getCallingPid(),
454 IPCThreadState::self()->getCallingUid());
455 result.append(buffer);
456 } else {
457 Mutex::Autolock lock(mLock);
458 for (int i = 0, n = mClients.size(); i < n; ++i) {
459 sp<Client> c = mClients[i].promote();
460 if (c != 0) c->dump(fd, args);
461 }
462 result.append(" Files opened and/or mapped:\n");
463 snprintf(buffer, SIZE, "/proc/%d/maps", myTid());
464 FILE *f = fopen(buffer, "r");
465 if (f) {
466 while (!feof(f)) {
467 fgets(buffer, SIZE, f);
468 if (strstr(buffer, " /sdcard/") ||
469 strstr(buffer, " /system/sounds/") ||
470 strstr(buffer, " /system/media/")) {
471 result.append(" ");
472 result.append(buffer);
473 }
474 }
475 fclose(f);
476 } else {
477 result.append("couldn't open ");
478 result.append(buffer);
479 result.append("\n");
480 }
481
482 snprintf(buffer, SIZE, "/proc/%d/fd", myTid());
483 DIR *d = opendir(buffer);
484 if (d) {
485 struct dirent *ent;
486 while((ent = readdir(d)) != NULL) {
487 if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
488 snprintf(buffer, SIZE, "/proc/%d/fd/%s", myTid(), ent->d_name);
489 struct stat s;
490 if (lstat(buffer, &s) == 0) {
491 if ((s.st_mode & S_IFMT) == S_IFLNK) {
492 char linkto[256];
493 int len = readlink(buffer, linkto, sizeof(linkto));
494 if(len > 0) {
495 if(len > 255) {
496 linkto[252] = '.';
497 linkto[253] = '.';
498 linkto[254] = '.';
499 linkto[255] = 0;
500 } else {
501 linkto[len] = 0;
502 }
503 if (strstr(linkto, "/sdcard/") == linkto ||
504 strstr(linkto, "/system/sounds/") == linkto ||
505 strstr(linkto, "/system/media/") == linkto) {
506 result.append(" ");
507 result.append(buffer);
508 result.append(" -> ");
509 result.append(linkto);
510 result.append("\n");
511 }
512 }
513 } else {
514 result.append(" unexpected type for ");
515 result.append(buffer);
516 result.append("\n");
517 }
518 }
519 }
520 }
521 closedir(d);
522 } else {
523 result.append("couldn't open ");
524 result.append(buffer);
525 result.append("\n");
526 }
527
528#if defined(__arm__)
529 bool dumpMem = false;
530 for (size_t i = 0; i < args.size(); i++) {
531 if (args[i] == String16("-m")) {
532 dumpMem = true;
533 }
534 }
535 if (dumpMem) {
536 memStatus(fd, args);
537 }
538#endif
539 }
540 write(fd, result.string(), result.size());
541 return NO_ERROR;
542}
543
544void MediaPlayerService::removeClient(wp<Client> client)
545{
546 Mutex::Autolock lock(mLock);
547 mClients.remove(client);
548}
549
550MediaPlayerService::Client::Client(const sp<MediaPlayerService>& service, pid_t pid,
551 int32_t connId, const sp<IMediaPlayerClient>& client)
552{
553 LOGV("Client(%d) constructor", connId);
554 mPid = pid;
555 mConnId = connId;
556 mService = service;
557 mClient = client;
558 mLoop = false;
559 mStatus = NO_INIT;
560#if CALLBACK_ANTAGONIZER
561 LOGD("create Antagonizer");
562 mAntagonizer = new Antagonizer(notify, this);
563#endif
564}
565
566MediaPlayerService::Client::~Client()
567{
568 LOGV("Client(%d) destructor pid = %d", mConnId, mPid);
569 mAudioOutput.clear();
570 wp<Client> client(this);
571 disconnect();
572 mService->removeClient(client);
573}
574
575void MediaPlayerService::Client::disconnect()
576{
577 LOGV("disconnect(%d) from pid %d", mConnId, mPid);
578 // grab local reference and clear main reference to prevent future
579 // access to object
580 sp<MediaPlayerBase> p;
581 {
582 Mutex::Autolock l(mLock);
583 p = mPlayer;
584 }
Dave Sparks795fa582009-03-24 17:57:12 -0700585 mClient.clear();
Andreas Huber20111aa2009-07-14 16:56:47 -0700586
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800587 mPlayer.clear();
588
589 // clear the notification to prevent callbacks to dead client
590 // and reset the player. We assume the player will serialize
591 // access to itself if necessary.
592 if (p != 0) {
593 p->setNotifyCallback(0, 0);
594#if CALLBACK_ANTAGONIZER
595 LOGD("kill Antagonizer");
596 mAntagonizer->kill();
597#endif
598 p->reset();
599 }
600
601 IPCThreadState::self()->flushCommands();
602}
603
Andreas Huber47f59cf2009-08-07 09:30:32 -0700604static player_type getDefaultPlayerType() {
Andreas Huber8f0e4aa2009-09-11 09:54:52 -0700605#if BUILD_WITH_FULL_STAGEFRIGHT
Andreas Huber47f59cf2009-08-07 09:30:32 -0700606 char value[PROPERTY_VALUE_MAX];
607 if (property_get("media.stagefright.enable-player", value, NULL)
608 && (!strcmp(value, "1") || !strcasecmp(value, "true"))) {
609 return STAGEFRIGHT_PLAYER;
610 }
Andreas Huber8f0e4aa2009-09-11 09:54:52 -0700611#endif
Andreas Huber47f59cf2009-08-07 09:30:32 -0700612
613 return PV_PLAYER;
614}
615
James Dong148c1a22009-09-06 14:29:45 -0700616player_type getPlayerType(int fd, int64_t offset, int64_t length)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800617{
618 char buf[20];
619 lseek(fd, offset, SEEK_SET);
620 read(fd, buf, sizeof(buf));
621 lseek(fd, offset, SEEK_SET);
622
623 long ident = *((long*)buf);
624
625 // Ogg vorbis?
626 if (ident == 0x5367674f) // 'OggS'
627 return VORBIS_PLAYER;
628
629 // Some kind of MIDI?
630 EAS_DATA_HANDLE easdata;
631 if (EAS_Init(&easdata) == EAS_SUCCESS) {
632 EAS_FILE locator;
633 locator.path = NULL;
634 locator.fd = fd;
635 locator.offset = offset;
636 locator.length = length;
637 EAS_HANDLE eashandle;
638 if (EAS_OpenFile(easdata, &locator, &eashandle) == EAS_SUCCESS) {
639 EAS_CloseFile(easdata, eashandle);
640 EAS_Shutdown(easdata);
641 return SONIVOX_PLAYER;
642 }
643 EAS_Shutdown(easdata);
644 }
645
Andreas Huber47f59cf2009-08-07 09:30:32 -0700646 return getDefaultPlayerType();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800647}
648
James Dong148c1a22009-09-06 14:29:45 -0700649player_type getPlayerType(const char* url)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800650{
Nicolas Catania14d27472009-07-13 14:37:49 -0700651 if (TestPlayerStub::canBeUsed(url)) {
652 return TEST_PLAYER;
653 }
654
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800655 // use MidiFile for MIDI extensions
656 int lenURL = strlen(url);
657 for (int i = 0; i < NELEM(FILE_EXTS); ++i) {
658 int len = strlen(FILE_EXTS[i].extension);
659 int start = lenURL - len;
660 if (start > 0) {
661 if (!strncmp(url + start, FILE_EXTS[i].extension, len)) {
662 return FILE_EXTS[i].playertype;
663 }
664 }
665 }
666
Andreas Huber47f59cf2009-08-07 09:30:32 -0700667 return getDefaultPlayerType();
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800668}
669
670static sp<MediaPlayerBase> createPlayer(player_type playerType, void* cookie,
671 notify_callback_f notifyFunc)
672{
673 sp<MediaPlayerBase> p;
674 switch (playerType) {
Jean-Baptiste Queru6c5b2102009-03-21 11:40:18 -0700675#ifndef NO_OPENCORE
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800676 case PV_PLAYER:
677 LOGV(" create PVPlayer");
678 p = new PVPlayer();
679 break;
Jean-Baptiste Queru6c5b2102009-03-21 11:40:18 -0700680#endif
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800681 case SONIVOX_PLAYER:
682 LOGV(" create MidiFile");
683 p = new MidiFile();
684 break;
685 case VORBIS_PLAYER:
686 LOGV(" create VorbisPlayer");
687 p = new VorbisPlayer();
688 break;
Andreas Huber8f0e4aa2009-09-11 09:54:52 -0700689#if BUILD_WITH_FULL_STAGEFRIGHT
Andreas Huber20111aa2009-07-14 16:56:47 -0700690 case STAGEFRIGHT_PLAYER:
691 LOGV(" create StagefrightPlayer");
692 p = new StagefrightPlayer;
693 break;
Andreas Huber8f0e4aa2009-09-11 09:54:52 -0700694#endif
Nicolas Catania14d27472009-07-13 14:37:49 -0700695 case TEST_PLAYER:
696 LOGV("Create Test Player stub");
697 p = new TestPlayerStub();
698 break;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800699 }
700 if (p != NULL) {
701 if (p->initCheck() == NO_ERROR) {
702 p->setNotifyCallback(cookie, notifyFunc);
703 } else {
704 p.clear();
705 }
706 }
707 if (p == NULL) {
708 LOGE("Failed to create player object");
709 }
710 return p;
711}
712
713sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
714{
715 // determine if we have the right player type
716 sp<MediaPlayerBase> p = mPlayer;
717 if ((p != NULL) && (p->playerType() != playerType)) {
718 LOGV("delete player");
719 p.clear();
720 }
721 if (p == NULL) {
722 p = android::createPlayer(playerType, this, notify);
723 }
724 return p;
725}
726
727status_t MediaPlayerService::Client::setDataSource(const char *url)
728{
729 LOGV("setDataSource(%s)", url);
730 if (url == NULL)
731 return UNKNOWN_ERROR;
732
733 if (strncmp(url, "content://", 10) == 0) {
734 // get a filedescriptor for the content Uri and
735 // pass it to the setDataSource(fd) method
736
737 String16 url16(url);
738 int fd = android::openContentProviderFile(url16);
739 if (fd < 0)
740 {
741 LOGE("Couldn't open fd for %s", url);
742 return UNKNOWN_ERROR;
743 }
744 setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
745 close(fd);
746 return mStatus;
747 } else {
748 player_type playerType = getPlayerType(url);
749 LOGV("player type = %d", playerType);
750
751 // create the right type of player
752 sp<MediaPlayerBase> p = createPlayer(playerType);
753 if (p == NULL) return NO_INIT;
754
755 if (!p->hardwareOutput()) {
756 mAudioOutput = new AudioOutput();
757 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
758 }
759
760 // now set data source
761 LOGV(" setDataSource");
762 mStatus = p->setDataSource(url);
Nicolas Catania14d27472009-07-13 14:37:49 -0700763 if (mStatus == NO_ERROR) {
764 mPlayer = p;
765 } else {
766 LOGE(" error: %d", mStatus);
767 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800768 return mStatus;
769 }
770}
771
772status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
773{
774 LOGV("setDataSource fd=%d, offset=%lld, length=%lld", fd, offset, length);
775 struct stat sb;
776 int ret = fstat(fd, &sb);
777 if (ret != 0) {
778 LOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
779 return UNKNOWN_ERROR;
780 }
781
782 LOGV("st_dev = %llu", sb.st_dev);
783 LOGV("st_mode = %u", sb.st_mode);
784 LOGV("st_uid = %lu", sb.st_uid);
785 LOGV("st_gid = %lu", sb.st_gid);
786 LOGV("st_size = %llu", sb.st_size);
787
788 if (offset >= sb.st_size) {
789 LOGE("offset error");
790 ::close(fd);
791 return UNKNOWN_ERROR;
792 }
793 if (offset + length > sb.st_size) {
794 length = sb.st_size - offset;
795 LOGV("calculated length = %lld", length);
796 }
797
798 player_type playerType = getPlayerType(fd, offset, length);
799 LOGV("player type = %d", playerType);
800
801 // create the right type of player
802 sp<MediaPlayerBase> p = createPlayer(playerType);
803 if (p == NULL) return NO_INIT;
804
805 if (!p->hardwareOutput()) {
806 mAudioOutput = new AudioOutput();
807 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
808 }
809
810 // now set data source
811 mStatus = p->setDataSource(fd, offset, length);
812 if (mStatus == NO_ERROR) mPlayer = p;
813 return mStatus;
814}
815
816status_t MediaPlayerService::Client::setVideoSurface(const sp<ISurface>& surface)
817{
818 LOGV("[%d] setVideoSurface(%p)", mConnId, surface.get());
819 sp<MediaPlayerBase> p = getPlayer();
820 if (p == 0) return UNKNOWN_ERROR;
821 return p->setVideoSurface(surface);
822}
823
Nicolas Catania1d187f12009-05-12 23:25:55 -0700824status_t MediaPlayerService::Client::invoke(const Parcel& request,
825 Parcel *reply)
826{
827 sp<MediaPlayerBase> p = getPlayer();
828 if (p == NULL) return UNKNOWN_ERROR;
829 return p->invoke(request, reply);
830}
831
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700832// This call doesn't need to access the native player.
833status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
834{
835 status_t status;
nikoa64c8c72009-07-20 15:07:26 -0700836 media::Metadata::Filter allow, drop;
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700837
Nicolas Catania48290382009-07-10 13:53:06 -0700838 if (unmarshallFilter(filter, &allow, &status) &&
839 unmarshallFilter(filter, &drop, &status)) {
840 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -0700841
842 mMetadataAllow = allow;
843 mMetadataDrop = drop;
844 }
845 return status;
846}
847
Nicolas Catania48290382009-07-10 13:53:06 -0700848status_t MediaPlayerService::Client::getMetadata(
849 bool update_only, bool apply_filter, Parcel *reply)
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700850{
nikoa64c8c72009-07-20 15:07:26 -0700851 sp<MediaPlayerBase> player = getPlayer();
852 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania48290382009-07-10 13:53:06 -0700853
nikod608a812009-07-16 16:39:53 -0700854 status_t status;
855 // Placeholder for the return code, updated by the caller.
856 reply->writeInt32(-1);
857
nikoa64c8c72009-07-20 15:07:26 -0700858 media::Metadata::Filter ids;
Nicolas Catania48290382009-07-10 13:53:06 -0700859
860 // We don't block notifications while we fetch the data. We clear
861 // mMetadataUpdated first so we don't lose notifications happening
862 // during the rest of this call.
863 {
864 Mutex::Autolock lock(mLock);
865 if (update_only) {
nikod608a812009-07-16 16:39:53 -0700866 ids = mMetadataUpdated;
Nicolas Catania48290382009-07-10 13:53:06 -0700867 }
868 mMetadataUpdated.clear();
869 }
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700870
nikoa64c8c72009-07-20 15:07:26 -0700871 media::Metadata metadata(reply);
Nicolas Catania48290382009-07-10 13:53:06 -0700872
nikoa64c8c72009-07-20 15:07:26 -0700873 metadata.appendHeader();
874 status = player->getMetadata(ids, reply);
nikod608a812009-07-16 16:39:53 -0700875
876 if (status != OK) {
nikoa64c8c72009-07-20 15:07:26 -0700877 metadata.resetParcel();
nikod608a812009-07-16 16:39:53 -0700878 LOGE("getMetadata failed %d", status);
879 return status;
880 }
881
882 // FIXME: Implement filtering on the result. Not critical since
883 // filtering takes place on the update notifications already. This
884 // would be when all the metadata are fetch and a filter is set.
885
nikod608a812009-07-16 16:39:53 -0700886 // Everything is fine, update the metadata length.
nikoa64c8c72009-07-20 15:07:26 -0700887 metadata.updateLength();
nikod608a812009-07-16 16:39:53 -0700888 return OK;
Nicolas Catania8e1b6cc2009-07-09 09:21:33 -0700889}
890
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800891status_t MediaPlayerService::Client::prepareAsync()
892{
893 LOGV("[%d] prepareAsync", mConnId);
894 sp<MediaPlayerBase> p = getPlayer();
895 if (p == 0) return UNKNOWN_ERROR;
896 status_t ret = p->prepareAsync();
897#if CALLBACK_ANTAGONIZER
898 LOGD("start Antagonizer");
899 if (ret == NO_ERROR) mAntagonizer->start();
900#endif
901 return ret;
902}
903
904status_t MediaPlayerService::Client::start()
905{
906 LOGV("[%d] start", mConnId);
907 sp<MediaPlayerBase> p = getPlayer();
908 if (p == 0) return UNKNOWN_ERROR;
909 p->setLooping(mLoop);
910 return p->start();
911}
912
913status_t MediaPlayerService::Client::stop()
914{
915 LOGV("[%d] stop", mConnId);
916 sp<MediaPlayerBase> p = getPlayer();
917 if (p == 0) return UNKNOWN_ERROR;
918 return p->stop();
919}
920
921status_t MediaPlayerService::Client::pause()
922{
923 LOGV("[%d] pause", mConnId);
924 sp<MediaPlayerBase> p = getPlayer();
925 if (p == 0) return UNKNOWN_ERROR;
926 return p->pause();
927}
928
929status_t MediaPlayerService::Client::isPlaying(bool* state)
930{
931 *state = false;
932 sp<MediaPlayerBase> p = getPlayer();
933 if (p == 0) return UNKNOWN_ERROR;
934 *state = p->isPlaying();
935 LOGV("[%d] isPlaying: %d", mConnId, *state);
936 return NO_ERROR;
937}
938
939status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
940{
941 LOGV("getCurrentPosition");
942 sp<MediaPlayerBase> p = getPlayer();
943 if (p == 0) return UNKNOWN_ERROR;
944 status_t ret = p->getCurrentPosition(msec);
945 if (ret == NO_ERROR) {
946 LOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
947 } else {
948 LOGE("getCurrentPosition returned %d", ret);
949 }
950 return ret;
951}
952
953status_t MediaPlayerService::Client::getDuration(int *msec)
954{
955 LOGV("getDuration");
956 sp<MediaPlayerBase> p = getPlayer();
957 if (p == 0) return UNKNOWN_ERROR;
958 status_t ret = p->getDuration(msec);
959 if (ret == NO_ERROR) {
960 LOGV("[%d] getDuration = %d", mConnId, *msec);
961 } else {
962 LOGE("getDuration returned %d", ret);
963 }
964 return ret;
965}
966
967status_t MediaPlayerService::Client::seekTo(int msec)
968{
969 LOGV("[%d] seekTo(%d)", mConnId, msec);
970 sp<MediaPlayerBase> p = getPlayer();
971 if (p == 0) return UNKNOWN_ERROR;
972 return p->seekTo(msec);
973}
974
975status_t MediaPlayerService::Client::reset()
976{
977 LOGV("[%d] reset", mConnId);
978 sp<MediaPlayerBase> p = getPlayer();
979 if (p == 0) return UNKNOWN_ERROR;
980 return p->reset();
981}
982
983status_t MediaPlayerService::Client::setAudioStreamType(int type)
984{
985 LOGV("[%d] setAudioStreamType(%d)", mConnId, type);
986 // TODO: for hardware output, call player instead
987 Mutex::Autolock l(mLock);
988 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
989 return NO_ERROR;
990}
991
992status_t MediaPlayerService::Client::setLooping(int loop)
993{
994 LOGV("[%d] setLooping(%d)", mConnId, loop);
995 mLoop = loop;
996 sp<MediaPlayerBase> p = getPlayer();
997 if (p != 0) return p->setLooping(loop);
998 return NO_ERROR;
999}
1000
1001status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1002{
1003 LOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
1004 // TODO: for hardware output, call player instead
1005 Mutex::Autolock l(mLock);
1006 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1007 return NO_ERROR;
1008}
1009
Nicolas Catania48290382009-07-10 13:53:06 -07001010
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001011void MediaPlayerService::Client::notify(void* cookie, int msg, int ext1, int ext2)
1012{
1013 Client* client = static_cast<Client*>(cookie);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001014
1015 if (MEDIA_INFO == msg &&
Nicolas Catania48290382009-07-10 13:53:06 -07001016 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikoa64c8c72009-07-20 15:07:26 -07001017 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania48290382009-07-10 13:53:06 -07001018
1019 if(client->shouldDropMetadata(metadata_type)) {
1020 return;
1021 }
1022
1023 // Update the list of metadata that have changed. getMetadata
1024 // also access mMetadataUpdated and clears it.
1025 client->addNewMetadataUpdate(metadata_type);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001026 }
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001027 LOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
1028 client->mClient->notify(msg, ext1, ext2);
1029}
1030
Nicolas Catania48290382009-07-10 13:53:06 -07001031
nikoa64c8c72009-07-20 15:07:26 -07001032bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001033{
Nicolas Catania48290382009-07-10 13:53:06 -07001034 Mutex::Autolock lock(mLock);
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001035
Nicolas Catania48290382009-07-10 13:53:06 -07001036 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001037 return true;
1038 }
1039
Nicolas Catania48290382009-07-10 13:53:06 -07001040 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001041 return false;
Nicolas Catania48290382009-07-10 13:53:06 -07001042 } else {
Nicolas Cataniaa7e0e8b2009-07-08 08:57:42 -07001043 return true;
1044 }
1045}
1046
Nicolas Catania48290382009-07-10 13:53:06 -07001047
nikoa64c8c72009-07-20 15:07:26 -07001048void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania48290382009-07-10 13:53:06 -07001049 Mutex::Autolock lock(mLock);
1050 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1051 mMetadataUpdated.add(metadata_type);
1052 }
1053}
1054
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001055#if CALLBACK_ANTAGONIZER
1056const int Antagonizer::interval = 10000; // 10 msecs
1057
1058Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1059 mExit(false), mActive(false), mClient(client), mCb(cb)
1060{
1061 createThread(callbackThread, this);
1062}
1063
1064void Antagonizer::kill()
1065{
1066 Mutex::Autolock _l(mLock);
1067 mActive = false;
1068 mExit = true;
1069 mCondition.wait(mLock);
1070}
1071
1072int Antagonizer::callbackThread(void* user)
1073{
1074 LOGD("Antagonizer started");
1075 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1076 while (!p->mExit) {
1077 if (p->mActive) {
1078 LOGV("send event");
1079 p->mCb(p->mClient, 0, 0, 0);
1080 }
1081 usleep(interval);
1082 }
1083 Mutex::Autolock _l(p->mLock);
1084 p->mCondition.signal();
1085 LOGD("Antagonizer stopped");
1086 return 0;
1087}
1088#endif
1089
1090static size_t kDefaultHeapSize = 1024 * 1024; // 1MB
1091
1092sp<IMemory> MediaPlayerService::decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1093{
1094 LOGV("decode(%s)", url);
1095 sp<MemoryBase> mem;
1096 sp<MediaPlayerBase> player;
1097
1098 // Protect our precious, precious DRMd ringtones by only allowing
1099 // decoding of http, but not filesystem paths or content Uris.
1100 // If the application wants to decode those, it should open a
1101 // filedescriptor for them and use that.
1102 if (url != NULL && strncmp(url, "http://", 7) != 0) {
1103 LOGD("Can't decode %s by path, use filedescriptor instead", url);
1104 return mem;
1105 }
1106
1107 player_type playerType = getPlayerType(url);
1108 LOGV("player type = %d", playerType);
1109
1110 // create the right type of player
1111 sp<AudioCache> cache = new AudioCache(url);
1112 player = android::createPlayer(playerType, cache.get(), cache->notify);
1113 if (player == NULL) goto Exit;
1114 if (player->hardwareOutput()) goto Exit;
1115
1116 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1117
1118 // set data source
1119 if (player->setDataSource(url) != NO_ERROR) goto Exit;
1120
1121 LOGV("prepare");
1122 player->prepareAsync();
1123
1124 LOGV("wait for prepare");
1125 if (cache->wait() != NO_ERROR) goto Exit;
1126
1127 LOGV("start");
1128 player->start();
1129
1130 LOGV("wait for playback complete");
1131 if (cache->wait() != NO_ERROR) goto Exit;
1132
1133 mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1134 *pSampleRate = cache->sampleRate();
1135 *pNumChannels = cache->channelCount();
1136 *pFormat = cache->format();
1137 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1138
1139Exit:
1140 if (player != 0) player->reset();
1141 return mem;
1142}
1143
1144sp<IMemory> MediaPlayerService::decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1145{
1146 LOGV("decode(%d, %lld, %lld)", fd, offset, length);
1147 sp<MemoryBase> mem;
1148 sp<MediaPlayerBase> player;
1149
1150 player_type playerType = getPlayerType(fd, offset, length);
1151 LOGV("player type = %d", playerType);
1152
1153 // create the right type of player
1154 sp<AudioCache> cache = new AudioCache("decode_fd");
1155 player = android::createPlayer(playerType, cache.get(), cache->notify);
1156 if (player == NULL) goto Exit;
1157 if (player->hardwareOutput()) goto Exit;
1158
1159 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1160
1161 // set data source
1162 if (player->setDataSource(fd, offset, length) != NO_ERROR) goto Exit;
1163
1164 LOGV("prepare");
1165 player->prepareAsync();
1166
1167 LOGV("wait for prepare");
1168 if (cache->wait() != NO_ERROR) goto Exit;
1169
1170 LOGV("start");
1171 player->start();
1172
1173 LOGV("wait for playback complete");
1174 if (cache->wait() != NO_ERROR) goto Exit;
1175
1176 mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1177 *pSampleRate = cache->sampleRate();
1178 *pNumChannels = cache->channelCount();
1179 *pFormat = cache->format();
1180 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1181
1182Exit:
1183 if (player != 0) player->reset();
1184 ::close(fd);
1185 return mem;
1186}
1187
1188#undef LOG_TAG
1189#define LOG_TAG "AudioSink"
1190MediaPlayerService::AudioOutput::AudioOutput()
Andreas Huber20111aa2009-07-14 16:56:47 -07001191 : mCallback(NULL),
1192 mCallbackCookie(NULL) {
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001193 mTrack = 0;
1194 mStreamType = AudioSystem::MUSIC;
1195 mLeftVolume = 1.0;
1196 mRightVolume = 1.0;
1197 mLatency = 0;
1198 mMsecsPerFrame = 0;
1199 setMinBufferCount();
1200}
1201
1202MediaPlayerService::AudioOutput::~AudioOutput()
1203{
1204 close();
1205}
1206
1207void MediaPlayerService::AudioOutput::setMinBufferCount()
1208{
1209 char value[PROPERTY_VALUE_MAX];
1210 if (property_get("ro.kernel.qemu", value, 0)) {
1211 mIsOnEmulator = true;
1212 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1213 }
1214}
1215
1216bool MediaPlayerService::AudioOutput::isOnEmulator()
1217{
1218 setMinBufferCount();
1219 return mIsOnEmulator;
1220}
1221
1222int MediaPlayerService::AudioOutput::getMinBufferCount()
1223{
1224 setMinBufferCount();
1225 return mMinBufferCount;
1226}
1227
1228ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1229{
1230 if (mTrack == 0) return NO_INIT;
1231 return mTrack->frameCount() * frameSize();
1232}
1233
1234ssize_t MediaPlayerService::AudioOutput::frameCount() const
1235{
1236 if (mTrack == 0) return NO_INIT;
1237 return mTrack->frameCount();
1238}
1239
1240ssize_t MediaPlayerService::AudioOutput::channelCount() const
1241{
1242 if (mTrack == 0) return NO_INIT;
1243 return mTrack->channelCount();
1244}
1245
1246ssize_t MediaPlayerService::AudioOutput::frameSize() const
1247{
1248 if (mTrack == 0) return NO_INIT;
1249 return mTrack->frameSize();
1250}
1251
1252uint32_t MediaPlayerService::AudioOutput::latency () const
1253{
1254 return mLatency;
1255}
1256
1257float MediaPlayerService::AudioOutput::msecsPerFrame() const
1258{
1259 return mMsecsPerFrame;
1260}
1261
Andreas Huber20111aa2009-07-14 16:56:47 -07001262status_t MediaPlayerService::AudioOutput::open(
1263 uint32_t sampleRate, int channelCount, int format, int bufferCount,
1264 AudioCallback cb, void *cookie)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001265{
Andreas Huber20111aa2009-07-14 16:56:47 -07001266 mCallback = cb;
1267 mCallbackCookie = cookie;
1268
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001269 // Check argument "bufferCount" against the mininum buffer count
1270 if (bufferCount < mMinBufferCount) {
1271 LOGD("bufferCount (%d) is too small and increased to %d", bufferCount, mMinBufferCount);
1272 bufferCount = mMinBufferCount;
1273
1274 }
1275 LOGV("open(%u, %d, %d, %d)", sampleRate, channelCount, format, bufferCount);
1276 if (mTrack) close();
1277 int afSampleRate;
1278 int afFrameCount;
1279 int frameCount;
1280
1281 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1282 return NO_INIT;
1283 }
1284 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1285 return NO_INIT;
1286 }
1287
1288 frameCount = (sampleRate*afFrameCount*bufferCount)/afSampleRate;
Andreas Huber20111aa2009-07-14 16:56:47 -07001289
1290 AudioTrack *t;
1291 if (mCallback != NULL) {
1292 t = new AudioTrack(
Eric Laurentc2f1f072009-07-17 12:17:14 -07001293 mStreamType,
1294 sampleRate,
1295 format,
1296 (channelCount == 2) ? AudioSystem::CHANNEL_OUT_STEREO : AudioSystem::CHANNEL_OUT_MONO,
1297 frameCount,
1298 0 /* flags */,
1299 CallbackWrapper,
1300 this);
Andreas Huber20111aa2009-07-14 16:56:47 -07001301 } else {
1302 t = new AudioTrack(
Eric Laurentc2f1f072009-07-17 12:17:14 -07001303 mStreamType,
1304 sampleRate,
1305 format,
1306 (channelCount == 2) ? AudioSystem::CHANNEL_OUT_STEREO : AudioSystem::CHANNEL_OUT_MONO,
1307 frameCount);
Andreas Huber20111aa2009-07-14 16:56:47 -07001308 }
1309
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001310 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1311 LOGE("Unable to create audio track");
1312 delete t;
1313 return NO_INIT;
1314 }
1315
1316 LOGV("setVolume");
1317 t->setVolume(mLeftVolume, mRightVolume);
1318 mMsecsPerFrame = 1.e3 / (float) sampleRate;
1319 mLatency = t->latency() + kAudioVideoDelayMs;
1320 mTrack = t;
1321 return NO_ERROR;
1322}
1323
1324void MediaPlayerService::AudioOutput::start()
1325{
1326 LOGV("start");
1327 if (mTrack) {
1328 mTrack->setVolume(mLeftVolume, mRightVolume);
1329 mTrack->start();
1330 }
1331}
1332
1333ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size)
1334{
Andreas Huber20111aa2009-07-14 16:56:47 -07001335 LOG_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
1336
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001337 //LOGV("write(%p, %u)", buffer, size);
1338 if (mTrack) return mTrack->write(buffer, size);
1339 return NO_INIT;
1340}
1341
1342void MediaPlayerService::AudioOutput::stop()
1343{
1344 LOGV("stop");
1345 if (mTrack) mTrack->stop();
1346}
1347
1348void MediaPlayerService::AudioOutput::flush()
1349{
1350 LOGV("flush");
1351 if (mTrack) mTrack->flush();
1352}
1353
1354void MediaPlayerService::AudioOutput::pause()
1355{
1356 LOGV("pause");
1357 if (mTrack) mTrack->pause();
1358}
1359
1360void MediaPlayerService::AudioOutput::close()
1361{
1362 LOGV("close");
1363 delete mTrack;
1364 mTrack = 0;
1365}
1366
1367void MediaPlayerService::AudioOutput::setVolume(float left, float right)
1368{
1369 LOGV("setVolume(%f, %f)", left, right);
1370 mLeftVolume = left;
1371 mRightVolume = right;
1372 if (mTrack) {
1373 mTrack->setVolume(left, right);
1374 }
1375}
1376
Andreas Huber20111aa2009-07-14 16:56:47 -07001377// static
1378void MediaPlayerService::AudioOutput::CallbackWrapper(
1379 int event, void *cookie, void *info) {
1380 if (event != AudioTrack::EVENT_MORE_DATA) {
1381 return;
1382 }
1383
1384 AudioOutput *me = (AudioOutput *)cookie;
1385 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
1386
1387 (*me->mCallback)(
1388 me, buffer->raw, buffer->size, me->mCallbackCookie);
1389}
1390
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001391#undef LOG_TAG
1392#define LOG_TAG "AudioCache"
1393MediaPlayerService::AudioCache::AudioCache(const char* name) :
1394 mChannelCount(0), mFrameCount(1024), mSampleRate(0), mSize(0),
1395 mError(NO_ERROR), mCommandComplete(false)
1396{
1397 // create ashmem heap
1398 mHeap = new MemoryHeapBase(kDefaultHeapSize, 0, name);
1399}
1400
1401uint32_t MediaPlayerService::AudioCache::latency () const
1402{
1403 return 0;
1404}
1405
1406float MediaPlayerService::AudioCache::msecsPerFrame() const
1407{
1408 return mMsecsPerFrame;
1409}
1410
Andreas Huber20111aa2009-07-14 16:56:47 -07001411status_t MediaPlayerService::AudioCache::open(
1412 uint32_t sampleRate, int channelCount, int format, int bufferCount,
1413 AudioCallback cb, void *cookie)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001414{
Andreas Huber20111aa2009-07-14 16:56:47 -07001415 if (cb != NULL) {
1416 return UNKNOWN_ERROR; // TODO: implement this.
1417 }
1418
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001419 LOGV("open(%u, %d, %d, %d)", sampleRate, channelCount, format, bufferCount);
1420 if (mHeap->getHeapID() < 0) return NO_INIT;
1421 mSampleRate = sampleRate;
1422 mChannelCount = (uint16_t)channelCount;
1423 mFormat = (uint16_t)format;
1424 mMsecsPerFrame = 1.e3 / (float) sampleRate;
1425 return NO_ERROR;
1426}
1427
1428ssize_t MediaPlayerService::AudioCache::write(const void* buffer, size_t size)
1429{
1430 LOGV("write(%p, %u)", buffer, size);
1431 if ((buffer == 0) || (size == 0)) return size;
1432
1433 uint8_t* p = static_cast<uint8_t*>(mHeap->getBase());
1434 if (p == NULL) return NO_INIT;
1435 p += mSize;
1436 LOGV("memcpy(%p, %p, %u)", p, buffer, size);
1437 if (mSize + size > mHeap->getSize()) {
1438 LOGE("Heap size overflow! req size: %d, max size: %d", (mSize + size), mHeap->getSize());
1439 size = mHeap->getSize() - mSize;
1440 }
1441 memcpy(p, buffer, size);
1442 mSize += size;
1443 return size;
1444}
1445
1446// call with lock held
1447status_t MediaPlayerService::AudioCache::wait()
1448{
1449 Mutex::Autolock lock(mLock);
1450 if (!mCommandComplete) {
1451 mSignal.wait(mLock);
1452 }
1453 mCommandComplete = false;
1454
1455 if (mError == NO_ERROR) {
1456 LOGV("wait - success");
1457 } else {
1458 LOGV("wait - error");
1459 }
1460 return mError;
1461}
1462
1463void MediaPlayerService::AudioCache::notify(void* cookie, int msg, int ext1, int ext2)
1464{
1465 LOGV("notify(%p, %d, %d, %d)", cookie, msg, ext1, ext2);
1466 AudioCache* p = static_cast<AudioCache*>(cookie);
1467
1468 // ignore buffering messages
1469 if (msg == MEDIA_BUFFERING_UPDATE) return;
1470
1471 // set error condition
1472 if (msg == MEDIA_ERROR) {
1473 LOGE("Error %d, %d occurred", ext1, ext2);
1474 p->mError = ext1;
1475 }
1476
1477 // wake up thread
1478 LOGV("wakeup thread");
1479 p->mCommandComplete = true;
1480 p->mSignal.signal();
1481}
1482
nikoa64c8c72009-07-20 15:07:26 -07001483} // namespace android