blob: eeb4e492104d2898c5d6202bfdfe20175b7f5b69 [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>
44#include <utils/Vector.h>
The Android Open Source Project9066cfe2009-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>
nikobc726922009-07-20 15:07:26 -070050#include <media/Metadata.h>
The Android Open Source Project9066cfe2009-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 Catania8f5fcab2009-07-13 14:37:49 -070060#include "TestPlayerStub.h"
Andreas Hubere46b7be2009-07-14 16:56:47 -070061#include "StagefrightPlayer.h"
Andreas Hubere46b7be2009-07-14 16:56:47 -070062
Andreas Hubere46b7be2009-07-14 16:56:47 -070063#include <OMX.h>
Nicolas Catania8f5fcab2009-07-13 14:37:49 -070064
The Android Open Source Project9066cfe2009-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 Cataniab2c69392009-07-08 08:57:42 -070077namespace {
nikobc726922009-07-20 15:07:26 -070078using android::media::Metadata;
Nicolas Cataniab2c69392009-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 Cataniab2c69392009-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
nikobc726922009-07-20 15:07:26 -070088// FIXME: Move all the metadata related function in the Metadata.cpp
niko89948372009-07-16 16:39:53 -070089
Nicolas Cataniab2c69392009-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,
nikobc726922009-07-20 15:07:26 -0700113 Metadata::Filter *filter,
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700114 status_t *status)
115{
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700116 int32_t val;
117 if (p.readInt32(&val) != OK)
Nicolas Cataniab2c69392009-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 Catania4df8b2c2009-07-10 13:53:06 -0700124 if( val > kMaxFilterSize || val < 0)
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700125 {
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700126 LOGE("Invalid filter len %d", val);
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700127 *status = BAD_VALUE;
128 return false;
129 }
130
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700131 const size_t num = val;
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700132
133 filter->clear();
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700134 filter->setCapacity(num);
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700135
nikobc726922009-07-20 15:07:26 -0700136 size_t size = num * sizeof(Metadata::Type);
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700137
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700138
139 if (p.dataAvail() < size)
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700140 {
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700141 LOGE("Filter too short expected %d but got %d", size, p.dataAvail());
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700142 *status = NOT_ENOUGH_DATA;
143 return false;
144 }
145
nikobc726922009-07-20 15:07:26 -0700146 const Metadata::Type *data =
147 static_cast<const Metadata::Type*>(p.readInplace(size));
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700148
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700149 if (NULL == data)
Nicolas Cataniab2c69392009-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 Catania4df8b2c2009-07-10 13:53:06 -0700159 for (size_t i = 0; i < num; ++i)
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700160 {
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700161 filter->add(*data);
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700162 ++data;
163 }
164 *status = OK;
165 return true;
166}
167
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700168// @param filter Of metadata type.
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700169// @param val To be searched.
170// @return true if a match was found.
nikobc726922009-07-20 15:07:26 -0700171bool findMetadata(const Metadata::Filter& filter, const int32_t val)
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700172{
173 // Deal with empty and ANY right away
174 if (filter.isEmpty()) return false;
nikobc726922009-07-20 15:07:26 -0700175 if (filter[0] == Metadata::kAny) return true;
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700176
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700177 return filter.indexOf(val) >= 0;
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700178}
179
180} // anonymous namespace
181
182
The Android Open Source Project9066cfe2009-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
204/* static */ const uint32_t MediaPlayerService::AudioOutput::kAudioVideoDelayMs = 96;
205/* 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 Queru680f8c72009-03-21 11:40:18 -0700226#ifndef NO_OPENCORE
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800227 sp<MediaRecorderClient> recorder = new MediaRecorderClient(pid);
Jean-Baptiste Queru680f8c72009-03-21 11:40:18 -0700228#else
229 sp<MediaRecorderClient> recorder = NULL;
230#endif
The Android Open Source Project9066cfe2009-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 Hubere46b7be2009-07-14 16:56:47 -0700276sp<IOMX> MediaPlayerService::createOMX() {
Andreas Hubere46b7be2009-07-14 16:56:47 -0700277 return new OMX;
Andreas Hubere46b7be2009-07-14 16:56:47 -0700278}
279
The Android Open Source Project9066cfe2009-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 Sparkscb9a44e2009-03-24 17:57:12 -0700585 mClient.clear();
Andreas Hubere46b7be2009-07-14 16:56:47 -0700586
The Android Open Source Project9066cfe2009-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 Huber0d596d42009-08-07 09:30:32 -0700604static player_type getDefaultPlayerType() {
605 char value[PROPERTY_VALUE_MAX];
606 if (property_get("media.stagefright.enable-player", value, NULL)
607 && (!strcmp(value, "1") || !strcasecmp(value, "true"))) {
608 return STAGEFRIGHT_PLAYER;
609 }
610
611 return PV_PLAYER;
612}
613
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800614static player_type getPlayerType(int fd, int64_t offset, int64_t length)
615{
616 char buf[20];
617 lseek(fd, offset, SEEK_SET);
618 read(fd, buf, sizeof(buf));
619 lseek(fd, offset, SEEK_SET);
620
621 long ident = *((long*)buf);
622
623 // Ogg vorbis?
624 if (ident == 0x5367674f) // 'OggS'
625 return VORBIS_PLAYER;
626
627 // Some kind of MIDI?
628 EAS_DATA_HANDLE easdata;
629 if (EAS_Init(&easdata) == EAS_SUCCESS) {
630 EAS_FILE locator;
631 locator.path = NULL;
632 locator.fd = fd;
633 locator.offset = offset;
634 locator.length = length;
635 EAS_HANDLE eashandle;
636 if (EAS_OpenFile(easdata, &locator, &eashandle) == EAS_SUCCESS) {
637 EAS_CloseFile(easdata, eashandle);
638 EAS_Shutdown(easdata);
639 return SONIVOX_PLAYER;
640 }
641 EAS_Shutdown(easdata);
642 }
643
Andreas Huber0d596d42009-08-07 09:30:32 -0700644 return getDefaultPlayerType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800645}
646
647static player_type getPlayerType(const char* url)
648{
Nicolas Catania8f5fcab2009-07-13 14:37:49 -0700649 if (TestPlayerStub::canBeUsed(url)) {
650 return TEST_PLAYER;
651 }
652
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800653 // use MidiFile for MIDI extensions
654 int lenURL = strlen(url);
655 for (int i = 0; i < NELEM(FILE_EXTS); ++i) {
656 int len = strlen(FILE_EXTS[i].extension);
657 int start = lenURL - len;
658 if (start > 0) {
659 if (!strncmp(url + start, FILE_EXTS[i].extension, len)) {
660 return FILE_EXTS[i].playertype;
661 }
662 }
663 }
664
Andreas Huber0d596d42009-08-07 09:30:32 -0700665 return getDefaultPlayerType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800666}
667
668static sp<MediaPlayerBase> createPlayer(player_type playerType, void* cookie,
669 notify_callback_f notifyFunc)
670{
671 sp<MediaPlayerBase> p;
672 switch (playerType) {
Jean-Baptiste Queru680f8c72009-03-21 11:40:18 -0700673#ifndef NO_OPENCORE
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800674 case PV_PLAYER:
675 LOGV(" create PVPlayer");
676 p = new PVPlayer();
677 break;
Jean-Baptiste Queru680f8c72009-03-21 11:40:18 -0700678#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800679 case SONIVOX_PLAYER:
680 LOGV(" create MidiFile");
681 p = new MidiFile();
682 break;
683 case VORBIS_PLAYER:
684 LOGV(" create VorbisPlayer");
685 p = new VorbisPlayer();
686 break;
Andreas Hubere46b7be2009-07-14 16:56:47 -0700687 case STAGEFRIGHT_PLAYER:
688 LOGV(" create StagefrightPlayer");
689 p = new StagefrightPlayer;
690 break;
Nicolas Catania8f5fcab2009-07-13 14:37:49 -0700691 case TEST_PLAYER:
692 LOGV("Create Test Player stub");
693 p = new TestPlayerStub();
694 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800695 }
696 if (p != NULL) {
697 if (p->initCheck() == NO_ERROR) {
698 p->setNotifyCallback(cookie, notifyFunc);
699 } else {
700 p.clear();
701 }
702 }
703 if (p == NULL) {
704 LOGE("Failed to create player object");
705 }
706 return p;
707}
708
709sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
710{
711 // determine if we have the right player type
712 sp<MediaPlayerBase> p = mPlayer;
713 if ((p != NULL) && (p->playerType() != playerType)) {
714 LOGV("delete player");
715 p.clear();
716 }
717 if (p == NULL) {
718 p = android::createPlayer(playerType, this, notify);
719 }
720 return p;
721}
722
723status_t MediaPlayerService::Client::setDataSource(const char *url)
724{
725 LOGV("setDataSource(%s)", url);
726 if (url == NULL)
727 return UNKNOWN_ERROR;
728
729 if (strncmp(url, "content://", 10) == 0) {
730 // get a filedescriptor for the content Uri and
731 // pass it to the setDataSource(fd) method
732
733 String16 url16(url);
734 int fd = android::openContentProviderFile(url16);
735 if (fd < 0)
736 {
737 LOGE("Couldn't open fd for %s", url);
738 return UNKNOWN_ERROR;
739 }
740 setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
741 close(fd);
742 return mStatus;
743 } else {
744 player_type playerType = getPlayerType(url);
745 LOGV("player type = %d", playerType);
746
747 // create the right type of player
748 sp<MediaPlayerBase> p = createPlayer(playerType);
749 if (p == NULL) return NO_INIT;
750
751 if (!p->hardwareOutput()) {
752 mAudioOutput = new AudioOutput();
753 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
754 }
755
756 // now set data source
757 LOGV(" setDataSource");
758 mStatus = p->setDataSource(url);
Nicolas Catania8f5fcab2009-07-13 14:37:49 -0700759 if (mStatus == NO_ERROR) {
760 mPlayer = p;
761 } else {
762 LOGE(" error: %d", mStatus);
763 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800764 return mStatus;
765 }
766}
767
768status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
769{
770 LOGV("setDataSource fd=%d, offset=%lld, length=%lld", fd, offset, length);
771 struct stat sb;
772 int ret = fstat(fd, &sb);
773 if (ret != 0) {
774 LOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
775 return UNKNOWN_ERROR;
776 }
777
778 LOGV("st_dev = %llu", sb.st_dev);
779 LOGV("st_mode = %u", sb.st_mode);
780 LOGV("st_uid = %lu", sb.st_uid);
781 LOGV("st_gid = %lu", sb.st_gid);
782 LOGV("st_size = %llu", sb.st_size);
783
784 if (offset >= sb.st_size) {
785 LOGE("offset error");
786 ::close(fd);
787 return UNKNOWN_ERROR;
788 }
789 if (offset + length > sb.st_size) {
790 length = sb.st_size - offset;
791 LOGV("calculated length = %lld", length);
792 }
793
794 player_type playerType = getPlayerType(fd, offset, length);
795 LOGV("player type = %d", playerType);
796
797 // create the right type of player
798 sp<MediaPlayerBase> p = createPlayer(playerType);
799 if (p == NULL) return NO_INIT;
800
801 if (!p->hardwareOutput()) {
802 mAudioOutput = new AudioOutput();
803 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
804 }
805
806 // now set data source
807 mStatus = p->setDataSource(fd, offset, length);
808 if (mStatus == NO_ERROR) mPlayer = p;
809 return mStatus;
810}
811
812status_t MediaPlayerService::Client::setVideoSurface(const sp<ISurface>& surface)
813{
814 LOGV("[%d] setVideoSurface(%p)", mConnId, surface.get());
815 sp<MediaPlayerBase> p = getPlayer();
816 if (p == 0) return UNKNOWN_ERROR;
817 return p->setVideoSurface(surface);
818}
819
Nicolas Catania20cb94e2009-05-12 23:25:55 -0700820status_t MediaPlayerService::Client::invoke(const Parcel& request,
821 Parcel *reply)
822{
823 sp<MediaPlayerBase> p = getPlayer();
824 if (p == NULL) return UNKNOWN_ERROR;
825 return p->invoke(request, reply);
826}
827
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700828// This call doesn't need to access the native player.
829status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
830{
831 status_t status;
nikobc726922009-07-20 15:07:26 -0700832 media::Metadata::Filter allow, drop;
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700833
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700834 if (unmarshallFilter(filter, &allow, &status) &&
835 unmarshallFilter(filter, &drop, &status)) {
836 Mutex::Autolock lock(mLock);
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700837
838 mMetadataAllow = allow;
839 mMetadataDrop = drop;
840 }
841 return status;
842}
843
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700844status_t MediaPlayerService::Client::getMetadata(
845 bool update_only, bool apply_filter, Parcel *reply)
Nicolas Catania5d55c712009-07-09 09:21:33 -0700846{
nikobc726922009-07-20 15:07:26 -0700847 sp<MediaPlayerBase> player = getPlayer();
848 if (player == 0) return UNKNOWN_ERROR;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700849
niko89948372009-07-16 16:39:53 -0700850 status_t status;
851 // Placeholder for the return code, updated by the caller.
852 reply->writeInt32(-1);
853
nikobc726922009-07-20 15:07:26 -0700854 media::Metadata::Filter ids;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700855
856 // We don't block notifications while we fetch the data. We clear
857 // mMetadataUpdated first so we don't lose notifications happening
858 // during the rest of this call.
859 {
860 Mutex::Autolock lock(mLock);
861 if (update_only) {
niko89948372009-07-16 16:39:53 -0700862 ids = mMetadataUpdated;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700863 }
864 mMetadataUpdated.clear();
865 }
Nicolas Catania5d55c712009-07-09 09:21:33 -0700866
nikobc726922009-07-20 15:07:26 -0700867 media::Metadata metadata(reply);
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700868
nikobc726922009-07-20 15:07:26 -0700869 metadata.appendHeader();
870 status = player->getMetadata(ids, reply);
niko89948372009-07-16 16:39:53 -0700871
872 if (status != OK) {
nikobc726922009-07-20 15:07:26 -0700873 metadata.resetParcel();
niko89948372009-07-16 16:39:53 -0700874 LOGE("getMetadata failed %d", status);
875 return status;
876 }
877
878 // FIXME: Implement filtering on the result. Not critical since
879 // filtering takes place on the update notifications already. This
880 // would be when all the metadata are fetch and a filter is set.
881
niko89948372009-07-16 16:39:53 -0700882 // Everything is fine, update the metadata length.
nikobc726922009-07-20 15:07:26 -0700883 metadata.updateLength();
niko89948372009-07-16 16:39:53 -0700884 return OK;
Nicolas Catania5d55c712009-07-09 09:21:33 -0700885}
886
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800887status_t MediaPlayerService::Client::prepareAsync()
888{
889 LOGV("[%d] prepareAsync", mConnId);
890 sp<MediaPlayerBase> p = getPlayer();
891 if (p == 0) return UNKNOWN_ERROR;
892 status_t ret = p->prepareAsync();
893#if CALLBACK_ANTAGONIZER
894 LOGD("start Antagonizer");
895 if (ret == NO_ERROR) mAntagonizer->start();
896#endif
897 return ret;
898}
899
900status_t MediaPlayerService::Client::start()
901{
902 LOGV("[%d] start", mConnId);
903 sp<MediaPlayerBase> p = getPlayer();
904 if (p == 0) return UNKNOWN_ERROR;
905 p->setLooping(mLoop);
906 return p->start();
907}
908
909status_t MediaPlayerService::Client::stop()
910{
911 LOGV("[%d] stop", mConnId);
912 sp<MediaPlayerBase> p = getPlayer();
913 if (p == 0) return UNKNOWN_ERROR;
914 return p->stop();
915}
916
917status_t MediaPlayerService::Client::pause()
918{
919 LOGV("[%d] pause", mConnId);
920 sp<MediaPlayerBase> p = getPlayer();
921 if (p == 0) return UNKNOWN_ERROR;
922 return p->pause();
923}
924
925status_t MediaPlayerService::Client::isPlaying(bool* state)
926{
927 *state = false;
928 sp<MediaPlayerBase> p = getPlayer();
929 if (p == 0) return UNKNOWN_ERROR;
930 *state = p->isPlaying();
931 LOGV("[%d] isPlaying: %d", mConnId, *state);
932 return NO_ERROR;
933}
934
935status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
936{
937 LOGV("getCurrentPosition");
938 sp<MediaPlayerBase> p = getPlayer();
939 if (p == 0) return UNKNOWN_ERROR;
940 status_t ret = p->getCurrentPosition(msec);
941 if (ret == NO_ERROR) {
942 LOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
943 } else {
944 LOGE("getCurrentPosition returned %d", ret);
945 }
946 return ret;
947}
948
949status_t MediaPlayerService::Client::getDuration(int *msec)
950{
951 LOGV("getDuration");
952 sp<MediaPlayerBase> p = getPlayer();
953 if (p == 0) return UNKNOWN_ERROR;
954 status_t ret = p->getDuration(msec);
955 if (ret == NO_ERROR) {
956 LOGV("[%d] getDuration = %d", mConnId, *msec);
957 } else {
958 LOGE("getDuration returned %d", ret);
959 }
960 return ret;
961}
962
963status_t MediaPlayerService::Client::seekTo(int msec)
964{
965 LOGV("[%d] seekTo(%d)", mConnId, msec);
966 sp<MediaPlayerBase> p = getPlayer();
967 if (p == 0) return UNKNOWN_ERROR;
968 return p->seekTo(msec);
969}
970
971status_t MediaPlayerService::Client::reset()
972{
973 LOGV("[%d] reset", mConnId);
974 sp<MediaPlayerBase> p = getPlayer();
975 if (p == 0) return UNKNOWN_ERROR;
976 return p->reset();
977}
978
979status_t MediaPlayerService::Client::setAudioStreamType(int type)
980{
981 LOGV("[%d] setAudioStreamType(%d)", mConnId, type);
982 // TODO: for hardware output, call player instead
983 Mutex::Autolock l(mLock);
984 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
985 return NO_ERROR;
986}
987
988status_t MediaPlayerService::Client::setLooping(int loop)
989{
990 LOGV("[%d] setLooping(%d)", mConnId, loop);
991 mLoop = loop;
992 sp<MediaPlayerBase> p = getPlayer();
993 if (p != 0) return p->setLooping(loop);
994 return NO_ERROR;
995}
996
997status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
998{
999 LOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
1000 // TODO: for hardware output, call player instead
1001 Mutex::Autolock l(mLock);
1002 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1003 return NO_ERROR;
1004}
1005
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001006
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001007void MediaPlayerService::Client::notify(void* cookie, int msg, int ext1, int ext2)
1008{
1009 Client* client = static_cast<Client*>(cookie);
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001010
1011 if (MEDIA_INFO == msg &&
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001012 MEDIA_INFO_METADATA_UPDATE == ext1) {
nikobc726922009-07-20 15:07:26 -07001013 const media::Metadata::Type metadata_type = ext2;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001014
1015 if(client->shouldDropMetadata(metadata_type)) {
1016 return;
1017 }
1018
1019 // Update the list of metadata that have changed. getMetadata
1020 // also access mMetadataUpdated and clears it.
1021 client->addNewMetadataUpdate(metadata_type);
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001022 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001023 LOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
1024 client->mClient->notify(msg, ext1, ext2);
1025}
1026
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001027
nikobc726922009-07-20 15:07:26 -07001028bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001029{
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001030 Mutex::Autolock lock(mLock);
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001031
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001032 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001033 return true;
1034 }
1035
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001036 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001037 return false;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001038 } else {
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001039 return true;
1040 }
1041}
1042
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001043
nikobc726922009-07-20 15:07:26 -07001044void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001045 Mutex::Autolock lock(mLock);
1046 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1047 mMetadataUpdated.add(metadata_type);
1048 }
1049}
1050
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001051#if CALLBACK_ANTAGONIZER
1052const int Antagonizer::interval = 10000; // 10 msecs
1053
1054Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1055 mExit(false), mActive(false), mClient(client), mCb(cb)
1056{
1057 createThread(callbackThread, this);
1058}
1059
1060void Antagonizer::kill()
1061{
1062 Mutex::Autolock _l(mLock);
1063 mActive = false;
1064 mExit = true;
1065 mCondition.wait(mLock);
1066}
1067
1068int Antagonizer::callbackThread(void* user)
1069{
1070 LOGD("Antagonizer started");
1071 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1072 while (!p->mExit) {
1073 if (p->mActive) {
1074 LOGV("send event");
1075 p->mCb(p->mClient, 0, 0, 0);
1076 }
1077 usleep(interval);
1078 }
1079 Mutex::Autolock _l(p->mLock);
1080 p->mCondition.signal();
1081 LOGD("Antagonizer stopped");
1082 return 0;
1083}
1084#endif
1085
1086static size_t kDefaultHeapSize = 1024 * 1024; // 1MB
1087
1088sp<IMemory> MediaPlayerService::decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1089{
1090 LOGV("decode(%s)", url);
1091 sp<MemoryBase> mem;
1092 sp<MediaPlayerBase> player;
1093
1094 // Protect our precious, precious DRMd ringtones by only allowing
1095 // decoding of http, but not filesystem paths or content Uris.
1096 // If the application wants to decode those, it should open a
1097 // filedescriptor for them and use that.
1098 if (url != NULL && strncmp(url, "http://", 7) != 0) {
1099 LOGD("Can't decode %s by path, use filedescriptor instead", url);
1100 return mem;
1101 }
1102
1103 player_type playerType = getPlayerType(url);
1104 LOGV("player type = %d", playerType);
1105
1106 // create the right type of player
1107 sp<AudioCache> cache = new AudioCache(url);
1108 player = android::createPlayer(playerType, cache.get(), cache->notify);
1109 if (player == NULL) goto Exit;
1110 if (player->hardwareOutput()) goto Exit;
1111
1112 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1113
1114 // set data source
1115 if (player->setDataSource(url) != NO_ERROR) goto Exit;
1116
1117 LOGV("prepare");
1118 player->prepareAsync();
1119
1120 LOGV("wait for prepare");
1121 if (cache->wait() != NO_ERROR) goto Exit;
1122
1123 LOGV("start");
1124 player->start();
1125
1126 LOGV("wait for playback complete");
1127 if (cache->wait() != NO_ERROR) goto Exit;
1128
1129 mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1130 *pSampleRate = cache->sampleRate();
1131 *pNumChannels = cache->channelCount();
1132 *pFormat = cache->format();
1133 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1134
1135Exit:
1136 if (player != 0) player->reset();
1137 return mem;
1138}
1139
1140sp<IMemory> MediaPlayerService::decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1141{
1142 LOGV("decode(%d, %lld, %lld)", fd, offset, length);
1143 sp<MemoryBase> mem;
1144 sp<MediaPlayerBase> player;
1145
1146 player_type playerType = getPlayerType(fd, offset, length);
1147 LOGV("player type = %d", playerType);
1148
1149 // create the right type of player
1150 sp<AudioCache> cache = new AudioCache("decode_fd");
1151 player = android::createPlayer(playerType, cache.get(), cache->notify);
1152 if (player == NULL) goto Exit;
1153 if (player->hardwareOutput()) goto Exit;
1154
1155 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1156
1157 // set data source
1158 if (player->setDataSource(fd, offset, length) != NO_ERROR) goto Exit;
1159
1160 LOGV("prepare");
1161 player->prepareAsync();
1162
1163 LOGV("wait for prepare");
1164 if (cache->wait() != NO_ERROR) goto Exit;
1165
1166 LOGV("start");
1167 player->start();
1168
1169 LOGV("wait for playback complete");
1170 if (cache->wait() != NO_ERROR) goto Exit;
1171
1172 mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1173 *pSampleRate = cache->sampleRate();
1174 *pNumChannels = cache->channelCount();
1175 *pFormat = cache->format();
1176 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1177
1178Exit:
1179 if (player != 0) player->reset();
1180 ::close(fd);
1181 return mem;
1182}
1183
1184#undef LOG_TAG
1185#define LOG_TAG "AudioSink"
1186MediaPlayerService::AudioOutput::AudioOutput()
Andreas Hubere46b7be2009-07-14 16:56:47 -07001187 : mCallback(NULL),
1188 mCallbackCookie(NULL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001189 mTrack = 0;
1190 mStreamType = AudioSystem::MUSIC;
1191 mLeftVolume = 1.0;
1192 mRightVolume = 1.0;
1193 mLatency = 0;
1194 mMsecsPerFrame = 0;
1195 setMinBufferCount();
1196}
1197
1198MediaPlayerService::AudioOutput::~AudioOutput()
1199{
1200 close();
1201}
1202
1203void MediaPlayerService::AudioOutput::setMinBufferCount()
1204{
1205 char value[PROPERTY_VALUE_MAX];
1206 if (property_get("ro.kernel.qemu", value, 0)) {
1207 mIsOnEmulator = true;
1208 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1209 }
1210}
1211
1212bool MediaPlayerService::AudioOutput::isOnEmulator()
1213{
1214 setMinBufferCount();
1215 return mIsOnEmulator;
1216}
1217
1218int MediaPlayerService::AudioOutput::getMinBufferCount()
1219{
1220 setMinBufferCount();
1221 return mMinBufferCount;
1222}
1223
1224ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1225{
1226 if (mTrack == 0) return NO_INIT;
1227 return mTrack->frameCount() * frameSize();
1228}
1229
1230ssize_t MediaPlayerService::AudioOutput::frameCount() const
1231{
1232 if (mTrack == 0) return NO_INIT;
1233 return mTrack->frameCount();
1234}
1235
1236ssize_t MediaPlayerService::AudioOutput::channelCount() const
1237{
1238 if (mTrack == 0) return NO_INIT;
1239 return mTrack->channelCount();
1240}
1241
1242ssize_t MediaPlayerService::AudioOutput::frameSize() const
1243{
1244 if (mTrack == 0) return NO_INIT;
1245 return mTrack->frameSize();
1246}
1247
1248uint32_t MediaPlayerService::AudioOutput::latency () const
1249{
1250 return mLatency;
1251}
1252
1253float MediaPlayerService::AudioOutput::msecsPerFrame() const
1254{
1255 return mMsecsPerFrame;
1256}
1257
Andreas Hubere46b7be2009-07-14 16:56:47 -07001258status_t MediaPlayerService::AudioOutput::open(
1259 uint32_t sampleRate, int channelCount, int format, int bufferCount,
1260 AudioCallback cb, void *cookie)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001261{
Andreas Hubere46b7be2009-07-14 16:56:47 -07001262 mCallback = cb;
1263 mCallbackCookie = cookie;
1264
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001265 // Check argument "bufferCount" against the mininum buffer count
1266 if (bufferCount < mMinBufferCount) {
1267 LOGD("bufferCount (%d) is too small and increased to %d", bufferCount, mMinBufferCount);
1268 bufferCount = mMinBufferCount;
1269
1270 }
1271 LOGV("open(%u, %d, %d, %d)", sampleRate, channelCount, format, bufferCount);
1272 if (mTrack) close();
1273 int afSampleRate;
1274 int afFrameCount;
1275 int frameCount;
1276
1277 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1278 return NO_INIT;
1279 }
1280 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1281 return NO_INIT;
1282 }
1283
1284 frameCount = (sampleRate*afFrameCount*bufferCount)/afSampleRate;
Andreas Hubere46b7be2009-07-14 16:56:47 -07001285
1286 AudioTrack *t;
1287 if (mCallback != NULL) {
1288 t = new AudioTrack(
Eric Laurenta553c252009-07-17 12:17:14 -07001289 mStreamType,
1290 sampleRate,
1291 format,
1292 (channelCount == 2) ? AudioSystem::CHANNEL_OUT_STEREO : AudioSystem::CHANNEL_OUT_MONO,
1293 frameCount,
1294 0 /* flags */,
1295 CallbackWrapper,
1296 this);
Andreas Hubere46b7be2009-07-14 16:56:47 -07001297 } else {
1298 t = new AudioTrack(
Eric Laurenta553c252009-07-17 12:17:14 -07001299 mStreamType,
1300 sampleRate,
1301 format,
1302 (channelCount == 2) ? AudioSystem::CHANNEL_OUT_STEREO : AudioSystem::CHANNEL_OUT_MONO,
1303 frameCount);
Andreas Hubere46b7be2009-07-14 16:56:47 -07001304 }
1305
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001306 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1307 LOGE("Unable to create audio track");
1308 delete t;
1309 return NO_INIT;
1310 }
1311
1312 LOGV("setVolume");
1313 t->setVolume(mLeftVolume, mRightVolume);
1314 mMsecsPerFrame = 1.e3 / (float) sampleRate;
1315 mLatency = t->latency() + kAudioVideoDelayMs;
1316 mTrack = t;
1317 return NO_ERROR;
1318}
1319
1320void MediaPlayerService::AudioOutput::start()
1321{
1322 LOGV("start");
1323 if (mTrack) {
1324 mTrack->setVolume(mLeftVolume, mRightVolume);
1325 mTrack->start();
1326 }
1327}
1328
1329ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size)
1330{
Andreas Hubere46b7be2009-07-14 16:56:47 -07001331 LOG_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
1332
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001333 //LOGV("write(%p, %u)", buffer, size);
1334 if (mTrack) return mTrack->write(buffer, size);
1335 return NO_INIT;
1336}
1337
1338void MediaPlayerService::AudioOutput::stop()
1339{
1340 LOGV("stop");
1341 if (mTrack) mTrack->stop();
1342}
1343
1344void MediaPlayerService::AudioOutput::flush()
1345{
1346 LOGV("flush");
1347 if (mTrack) mTrack->flush();
1348}
1349
1350void MediaPlayerService::AudioOutput::pause()
1351{
1352 LOGV("pause");
1353 if (mTrack) mTrack->pause();
1354}
1355
1356void MediaPlayerService::AudioOutput::close()
1357{
1358 LOGV("close");
1359 delete mTrack;
1360 mTrack = 0;
1361}
1362
1363void MediaPlayerService::AudioOutput::setVolume(float left, float right)
1364{
1365 LOGV("setVolume(%f, %f)", left, right);
1366 mLeftVolume = left;
1367 mRightVolume = right;
1368 if (mTrack) {
1369 mTrack->setVolume(left, right);
1370 }
1371}
1372
Andreas Hubere46b7be2009-07-14 16:56:47 -07001373// static
1374void MediaPlayerService::AudioOutput::CallbackWrapper(
1375 int event, void *cookie, void *info) {
1376 if (event != AudioTrack::EVENT_MORE_DATA) {
1377 return;
1378 }
1379
1380 AudioOutput *me = (AudioOutput *)cookie;
1381 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
1382
1383 (*me->mCallback)(
1384 me, buffer->raw, buffer->size, me->mCallbackCookie);
1385}
1386
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001387#undef LOG_TAG
1388#define LOG_TAG "AudioCache"
1389MediaPlayerService::AudioCache::AudioCache(const char* name) :
1390 mChannelCount(0), mFrameCount(1024), mSampleRate(0), mSize(0),
1391 mError(NO_ERROR), mCommandComplete(false)
1392{
1393 // create ashmem heap
1394 mHeap = new MemoryHeapBase(kDefaultHeapSize, 0, name);
1395}
1396
1397uint32_t MediaPlayerService::AudioCache::latency () const
1398{
1399 return 0;
1400}
1401
1402float MediaPlayerService::AudioCache::msecsPerFrame() const
1403{
1404 return mMsecsPerFrame;
1405}
1406
Andreas Hubere46b7be2009-07-14 16:56:47 -07001407status_t MediaPlayerService::AudioCache::open(
1408 uint32_t sampleRate, int channelCount, int format, int bufferCount,
1409 AudioCallback cb, void *cookie)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001410{
Andreas Hubere46b7be2009-07-14 16:56:47 -07001411 if (cb != NULL) {
1412 return UNKNOWN_ERROR; // TODO: implement this.
1413 }
1414
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001415 LOGV("open(%u, %d, %d, %d)", sampleRate, channelCount, format, bufferCount);
1416 if (mHeap->getHeapID() < 0) return NO_INIT;
1417 mSampleRate = sampleRate;
1418 mChannelCount = (uint16_t)channelCount;
1419 mFormat = (uint16_t)format;
1420 mMsecsPerFrame = 1.e3 / (float) sampleRate;
1421 return NO_ERROR;
1422}
1423
1424ssize_t MediaPlayerService::AudioCache::write(const void* buffer, size_t size)
1425{
1426 LOGV("write(%p, %u)", buffer, size);
1427 if ((buffer == 0) || (size == 0)) return size;
1428
1429 uint8_t* p = static_cast<uint8_t*>(mHeap->getBase());
1430 if (p == NULL) return NO_INIT;
1431 p += mSize;
1432 LOGV("memcpy(%p, %p, %u)", p, buffer, size);
1433 if (mSize + size > mHeap->getSize()) {
1434 LOGE("Heap size overflow! req size: %d, max size: %d", (mSize + size), mHeap->getSize());
1435 size = mHeap->getSize() - mSize;
1436 }
1437 memcpy(p, buffer, size);
1438 mSize += size;
1439 return size;
1440}
1441
1442// call with lock held
1443status_t MediaPlayerService::AudioCache::wait()
1444{
1445 Mutex::Autolock lock(mLock);
1446 if (!mCommandComplete) {
1447 mSignal.wait(mLock);
1448 }
1449 mCommandComplete = false;
1450
1451 if (mError == NO_ERROR) {
1452 LOGV("wait - success");
1453 } else {
1454 LOGV("wait - error");
1455 }
1456 return mError;
1457}
1458
1459void MediaPlayerService::AudioCache::notify(void* cookie, int msg, int ext1, int ext2)
1460{
1461 LOGV("notify(%p, %d, %d, %d)", cookie, msg, ext1, ext2);
1462 AudioCache* p = static_cast<AudioCache*>(cookie);
1463
1464 // ignore buffering messages
1465 if (msg == MEDIA_BUFFERING_UPDATE) return;
1466
1467 // set error condition
1468 if (msg == MEDIA_ERROR) {
1469 LOGE("Error %d, %d occurred", ext1, ext2);
1470 p->mError = ext1;
1471 }
1472
1473 // wake up thread
1474 LOGV("wakeup thread");
1475 p->mCommandComplete = true;
1476 p->mSignal.signal();
1477}
1478
nikobc726922009-07-20 15:07:26 -07001479} // namespace android