blob: c575f6c7a30ceaf6326dcd156040d5b9b0423787 [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>
Mathias Agopiana650aaa2009-06-03 17:32:49 -070032#include <cutils/properties.h>
33
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>
50#include <media/AudioTrack.h>
51
Nicolas Catania4df8b2c2009-07-10 13:53:06 -070052#include <utils/SortedVector.h>
53
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054#include "MediaRecorderClient.h"
55#include "MediaPlayerService.h"
56#include "MetadataRetrieverClient.h"
57
58#include "MidiFile.h"
59#include "VorbisPlayer.h"
60#include <media/PVPlayer.h>
Andreas Hubere46b7be2009-07-14 16:56:47 -070061#if USE_STAGEFRIGHT
62#include "StagefrightPlayer.h"
63#endif
64
65#ifdef BUILD_WITH_STAGEFRIGHT
66#include <OMX.h>
67#else
68#include <media/IOMX.h>
69#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070
71/* desktop Linux needs a little help with gettid() */
72#if defined(HAVE_GETTID) && !defined(HAVE_ANDROID_OS)
73#define __KERNEL__
74# include <linux/unistd.h>
75#ifdef _syscall0
76_syscall0(pid_t,gettid)
77#else
78pid_t gettid() { return syscall(__NR_gettid);}
79#endif
80#undef __KERNEL__
81#endif
82
Nicolas Cataniab2c69392009-07-08 08:57:42 -070083namespace {
84using android::status_t;
85using android::OK;
86using android::BAD_VALUE;
87using android::NOT_ENOUGH_DATA;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -070088using android::MetadataType;
Nicolas Cataniab2c69392009-07-08 08:57:42 -070089using android::Parcel;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -070090using android::SortedVector;
Nicolas Cataniab2c69392009-07-08 08:57:42 -070091
92// Max number of entries in the filter.
93const int kMaxFilterSize = 64; // I pulled that out of thin air.
94
95// Keep in sync with ANY in Metadata.java
96const int32_t kAny = 0;
97
Nicolas Cataniab2c69392009-07-08 08:57:42 -070098
99// Unmarshall a filter from a Parcel.
100// Filter format in a parcel:
101//
102// 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
103// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
104// | number of entries (n) |
105// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
106// | metadata type 1 |
107// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
108// | metadata type 2 |
109// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
110// ....
111// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
112// | metadata type n |
113// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
114//
115// @param p Parcel that should start with a filter.
116// @param[out] filter On exit contains the list of metadata type to be
117// filtered.
118// @param[out] status On exit contains the status code to be returned.
119// @return true if the parcel starts with a valid filter.
120bool unmarshallFilter(const Parcel& p,
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700121 SortedVector<MetadataType> *filter,
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700122 status_t *status)
123{
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700124 int32_t val;
125 if (p.readInt32(&val) != OK)
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700126 {
127 LOGE("Failed to read filter's length");
128 *status = NOT_ENOUGH_DATA;
129 return false;
130 }
131
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700132 if( val > kMaxFilterSize || val < 0)
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700133 {
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700134 LOGE("Invalid filter len %d", val);
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700135 *status = BAD_VALUE;
136 return false;
137 }
138
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700139 const size_t num = val;
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700140
141 filter->clear();
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700142 filter->setCapacity(num);
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700143
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700144 size_t size = num * sizeof(MetadataType);
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700145
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700146
147 if (p.dataAvail() < size)
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700148 {
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700149 LOGE("Filter too short expected %d but got %d", size, p.dataAvail());
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700150 *status = NOT_ENOUGH_DATA;
151 return false;
152 }
153
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700154 const MetadataType *data = static_cast<const MetadataType*>(p.readInplace(size));
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700155
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700156 if (NULL == data)
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700157 {
158 LOGE("Filter had no data");
159 *status = BAD_VALUE;
160 return false;
161 }
162
163 // TODO: The stl impl of vector would be more efficient here
164 // because it degenerates into a memcpy on pod types. Try to
165 // replace later or use stl::set.
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700166 for (size_t i = 0; i < num; ++i)
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700167 {
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700168 filter->add(*data);
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700169 ++data;
170 }
171 *status = OK;
172 return true;
173}
174
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700175// @param filter Of metadata type.
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700176// @param val To be searched.
177// @return true if a match was found.
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700178bool findMetadata(const SortedVector<MetadataType>& filter, const int32_t val)
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700179{
180 // Deal with empty and ANY right away
181 if (filter.isEmpty()) return false;
182 if (filter[0] == kAny) return true;
183
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700184 return filter.indexOf(val) >= 0;
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700185}
186
187} // anonymous namespace
188
189
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800190namespace android {
191
192// TODO: Temp hack until we can register players
193typedef struct {
194 const char *extension;
195 const player_type playertype;
196} extmap;
197extmap FILE_EXTS [] = {
Andreas Hubere46b7be2009-07-14 16:56:47 -0700198#if USE_STAGEFRIGHT
199 {".mp4", STAGEFRIGHT_PLAYER},
200 {".3gp", STAGEFRIGHT_PLAYER},
201#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800202 {".mid", SONIVOX_PLAYER},
203 {".midi", SONIVOX_PLAYER},
204 {".smf", SONIVOX_PLAYER},
205 {".xmf", SONIVOX_PLAYER},
206 {".imy", SONIVOX_PLAYER},
207 {".rtttl", SONIVOX_PLAYER},
208 {".rtx", SONIVOX_PLAYER},
209 {".ota", SONIVOX_PLAYER},
210 {".ogg", VORBIS_PLAYER},
211 {".oga", VORBIS_PLAYER},
212};
213
214// TODO: Find real cause of Audio/Video delay in PV framework and remove this workaround
215/* static */ const uint32_t MediaPlayerService::AudioOutput::kAudioVideoDelayMs = 96;
216/* static */ int MediaPlayerService::AudioOutput::mMinBufferCount = 4;
217/* static */ bool MediaPlayerService::AudioOutput::mIsOnEmulator = false;
218
219void MediaPlayerService::instantiate() {
220 defaultServiceManager()->addService(
221 String16("media.player"), new MediaPlayerService());
222}
223
224MediaPlayerService::MediaPlayerService()
225{
226 LOGV("MediaPlayerService created");
227 mNextConnId = 1;
228}
229
230MediaPlayerService::~MediaPlayerService()
231{
232 LOGV("MediaPlayerService destroyed");
233}
234
235sp<IMediaRecorder> MediaPlayerService::createMediaRecorder(pid_t pid)
236{
Jean-Baptiste Queru680f8c72009-03-21 11:40:18 -0700237#ifndef NO_OPENCORE
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800238 sp<MediaRecorderClient> recorder = new MediaRecorderClient(pid);
Jean-Baptiste Queru680f8c72009-03-21 11:40:18 -0700239#else
240 sp<MediaRecorderClient> recorder = NULL;
241#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800242 LOGV("Create new media recorder client from pid %d", pid);
243 return recorder;
244}
245
246sp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever(pid_t pid)
247{
248 sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
249 LOGV("Create new media retriever from pid %d", pid);
250 return retriever;
251}
252
253sp<IMediaPlayer> MediaPlayerService::create(pid_t pid, const sp<IMediaPlayerClient>& client, const char* url)
254{
255 int32_t connId = android_atomic_inc(&mNextConnId);
256 sp<Client> c = new Client(this, pid, connId, client);
257 LOGV("Create new client(%d) from pid %d, url=%s, connId=%d", connId, pid, url, connId);
258 if (NO_ERROR != c->setDataSource(url))
259 {
260 c.clear();
261 return c;
262 }
263 wp<Client> w = c;
264 Mutex::Autolock lock(mLock);
265 mClients.add(w);
266 return c;
267}
268
269sp<IMediaPlayer> MediaPlayerService::create(pid_t pid, const sp<IMediaPlayerClient>& client,
270 int fd, int64_t offset, int64_t length)
271{
272 int32_t connId = android_atomic_inc(&mNextConnId);
273 sp<Client> c = new Client(this, pid, connId, client);
274 LOGV("Create new client(%d) from pid %d, fd=%d, offset=%lld, length=%lld",
275 connId, pid, fd, offset, length);
276 if (NO_ERROR != c->setDataSource(fd, offset, length)) {
277 c.clear();
278 } else {
279 wp<Client> w = c;
280 Mutex::Autolock lock(mLock);
281 mClients.add(w);
282 }
283 ::close(fd);
284 return c;
285}
286
Andreas Hubere46b7be2009-07-14 16:56:47 -0700287sp<IOMX> MediaPlayerService::createOMX() {
288#ifdef BUILD_WITH_STAGEFRIGHT
289 return new OMX;
290#else
291 return NULL;
292#endif
293}
294
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800295status_t MediaPlayerService::AudioCache::dump(int fd, const Vector<String16>& args) const
296{
297 const size_t SIZE = 256;
298 char buffer[SIZE];
299 String8 result;
300
301 result.append(" AudioCache\n");
302 if (mHeap != 0) {
303 snprintf(buffer, 255, " heap base(%p), size(%d), flags(%d), device(%s)\n",
304 mHeap->getBase(), mHeap->getSize(), mHeap->getFlags(), mHeap->getDevice());
305 result.append(buffer);
306 }
307 snprintf(buffer, 255, " msec per frame(%f), channel count(%d), format(%d), frame count(%ld)\n",
308 mMsecsPerFrame, mChannelCount, mFormat, mFrameCount);
309 result.append(buffer);
310 snprintf(buffer, 255, " sample rate(%d), size(%d), error(%d), command complete(%s)\n",
311 mSampleRate, mSize, mError, mCommandComplete?"true":"false");
312 result.append(buffer);
313 ::write(fd, result.string(), result.size());
314 return NO_ERROR;
315}
316
317status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
318{
319 const size_t SIZE = 256;
320 char buffer[SIZE];
321 String8 result;
322
323 result.append(" AudioOutput\n");
324 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n",
325 mStreamType, mLeftVolume, mRightVolume);
326 result.append(buffer);
327 snprintf(buffer, 255, " msec per frame(%f), latency (%d)\n",
328 mMsecsPerFrame, mLatency);
329 result.append(buffer);
330 ::write(fd, result.string(), result.size());
331 if (mTrack != 0) {
332 mTrack->dump(fd, args);
333 }
334 return NO_ERROR;
335}
336
337status_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args) const
338{
339 const size_t SIZE = 256;
340 char buffer[SIZE];
341 String8 result;
342 result.append(" Client\n");
343 snprintf(buffer, 255, " pid(%d), connId(%d), status(%d), looping(%s)\n",
344 mPid, mConnId, mStatus, mLoop?"true": "false");
345 result.append(buffer);
346 write(fd, result.string(), result.size());
347 if (mAudioOutput != 0) {
348 mAudioOutput->dump(fd, args);
349 }
350 write(fd, "\n", 1);
351 return NO_ERROR;
352}
353
354static int myTid() {
355#ifdef HAVE_GETTID
356 return gettid();
357#else
358 return getpid();
359#endif
360}
361
362#if defined(__arm__)
363extern "C" void get_malloc_leak_info(uint8_t** info, size_t* overallSize,
364 size_t* infoSize, size_t* totalMemory, size_t* backtraceSize);
365extern "C" void free_malloc_leak_info(uint8_t* info);
366
367void memStatus(int fd, const Vector<String16>& args)
368{
369 const size_t SIZE = 256;
370 char buffer[SIZE];
371 String8 result;
372
373 typedef struct {
374 size_t size;
375 size_t dups;
376 intptr_t * backtrace;
377 } AllocEntry;
378
379 uint8_t *info = NULL;
380 size_t overallSize = 0;
381 size_t infoSize = 0;
382 size_t totalMemory = 0;
383 size_t backtraceSize = 0;
384
385 get_malloc_leak_info(&info, &overallSize, &infoSize, &totalMemory, &backtraceSize);
386 if (info) {
387 uint8_t *ptr = info;
388 size_t count = overallSize / infoSize;
389
390 snprintf(buffer, SIZE, " Allocation count %i\n", count);
391 result.append(buffer);
392
393 AllocEntry * entries = new AllocEntry[count];
394
395 for (size_t i = 0; i < count; i++) {
396 // Each entry should be size_t, size_t, intptr_t[backtraceSize]
397 AllocEntry *e = &entries[i];
398
399 e->size = *reinterpret_cast<size_t *>(ptr);
400 ptr += sizeof(size_t);
401
402 e->dups = *reinterpret_cast<size_t *>(ptr);
403 ptr += sizeof(size_t);
404
405 e->backtrace = reinterpret_cast<intptr_t *>(ptr);
406 ptr += sizeof(intptr_t) * backtraceSize;
407 }
408
409 // Now we need to sort the entries. They come sorted by size but
410 // not by stack trace which causes problems using diff.
411 bool moved;
412 do {
413 moved = false;
414 for (size_t i = 0; i < (count - 1); i++) {
415 AllocEntry *e1 = &entries[i];
416 AllocEntry *e2 = &entries[i+1];
417
418 bool swap = e1->size < e2->size;
419 if (e1->size == e2->size) {
420 for(size_t j = 0; j < backtraceSize; j++) {
421 if (e1->backtrace[j] == e2->backtrace[j]) {
422 continue;
423 }
424 swap = e1->backtrace[j] < e2->backtrace[j];
425 break;
426 }
427 }
428 if (swap) {
429 AllocEntry t = entries[i];
430 entries[i] = entries[i+1];
431 entries[i+1] = t;
432 moved = true;
433 }
434 }
435 } while (moved);
436
437 for (size_t i = 0; i < count; i++) {
438 AllocEntry *e = &entries[i];
439
440 snprintf(buffer, SIZE, "size %8i, dup %4i", e->size, e->dups);
441 result.append(buffer);
442 for (size_t ct = 0; (ct < backtraceSize) && e->backtrace[ct]; ct++) {
443 if (ct) {
444 result.append(", ");
445 }
446 snprintf(buffer, SIZE, "0x%08x", e->backtrace[ct]);
447 result.append(buffer);
448 }
449 result.append("\n");
450 }
451
452 delete[] entries;
453 free_malloc_leak_info(info);
454 }
455
456 write(fd, result.string(), result.size());
457}
458#endif
459
460status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
461{
462 const size_t SIZE = 256;
463 char buffer[SIZE];
464 String8 result;
465 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
466 snprintf(buffer, SIZE, "Permission Denial: "
467 "can't dump MediaPlayerService from pid=%d, uid=%d\n",
468 IPCThreadState::self()->getCallingPid(),
469 IPCThreadState::self()->getCallingUid());
470 result.append(buffer);
471 } else {
472 Mutex::Autolock lock(mLock);
473 for (int i = 0, n = mClients.size(); i < n; ++i) {
474 sp<Client> c = mClients[i].promote();
475 if (c != 0) c->dump(fd, args);
476 }
477 result.append(" Files opened and/or mapped:\n");
478 snprintf(buffer, SIZE, "/proc/%d/maps", myTid());
479 FILE *f = fopen(buffer, "r");
480 if (f) {
481 while (!feof(f)) {
482 fgets(buffer, SIZE, f);
483 if (strstr(buffer, " /sdcard/") ||
484 strstr(buffer, " /system/sounds/") ||
485 strstr(buffer, " /system/media/")) {
486 result.append(" ");
487 result.append(buffer);
488 }
489 }
490 fclose(f);
491 } else {
492 result.append("couldn't open ");
493 result.append(buffer);
494 result.append("\n");
495 }
496
497 snprintf(buffer, SIZE, "/proc/%d/fd", myTid());
498 DIR *d = opendir(buffer);
499 if (d) {
500 struct dirent *ent;
501 while((ent = readdir(d)) != NULL) {
502 if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
503 snprintf(buffer, SIZE, "/proc/%d/fd/%s", myTid(), ent->d_name);
504 struct stat s;
505 if (lstat(buffer, &s) == 0) {
506 if ((s.st_mode & S_IFMT) == S_IFLNK) {
507 char linkto[256];
508 int len = readlink(buffer, linkto, sizeof(linkto));
509 if(len > 0) {
510 if(len > 255) {
511 linkto[252] = '.';
512 linkto[253] = '.';
513 linkto[254] = '.';
514 linkto[255] = 0;
515 } else {
516 linkto[len] = 0;
517 }
518 if (strstr(linkto, "/sdcard/") == linkto ||
519 strstr(linkto, "/system/sounds/") == linkto ||
520 strstr(linkto, "/system/media/") == linkto) {
521 result.append(" ");
522 result.append(buffer);
523 result.append(" -> ");
524 result.append(linkto);
525 result.append("\n");
526 }
527 }
528 } else {
529 result.append(" unexpected type for ");
530 result.append(buffer);
531 result.append("\n");
532 }
533 }
534 }
535 }
536 closedir(d);
537 } else {
538 result.append("couldn't open ");
539 result.append(buffer);
540 result.append("\n");
541 }
542
543#if defined(__arm__)
544 bool dumpMem = false;
545 for (size_t i = 0; i < args.size(); i++) {
546 if (args[i] == String16("-m")) {
547 dumpMem = true;
548 }
549 }
550 if (dumpMem) {
551 memStatus(fd, args);
552 }
553#endif
554 }
555 write(fd, result.string(), result.size());
556 return NO_ERROR;
557}
558
559void MediaPlayerService::removeClient(wp<Client> client)
560{
561 Mutex::Autolock lock(mLock);
562 mClients.remove(client);
563}
564
565MediaPlayerService::Client::Client(const sp<MediaPlayerService>& service, pid_t pid,
566 int32_t connId, const sp<IMediaPlayerClient>& client)
567{
568 LOGV("Client(%d) constructor", connId);
569 mPid = pid;
570 mConnId = connId;
571 mService = service;
572 mClient = client;
573 mLoop = false;
574 mStatus = NO_INIT;
575#if CALLBACK_ANTAGONIZER
576 LOGD("create Antagonizer");
577 mAntagonizer = new Antagonizer(notify, this);
578#endif
579}
580
581MediaPlayerService::Client::~Client()
582{
583 LOGV("Client(%d) destructor pid = %d", mConnId, mPid);
584 mAudioOutput.clear();
585 wp<Client> client(this);
586 disconnect();
587 mService->removeClient(client);
588}
589
590void MediaPlayerService::Client::disconnect()
591{
592 LOGV("disconnect(%d) from pid %d", mConnId, mPid);
593 // grab local reference and clear main reference to prevent future
594 // access to object
595 sp<MediaPlayerBase> p;
596 {
597 Mutex::Autolock l(mLock);
598 p = mPlayer;
599 }
Dave Sparkscb9a44e2009-03-24 17:57:12 -0700600 mClient.clear();
Andreas Hubere46b7be2009-07-14 16:56:47 -0700601
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800602 mPlayer.clear();
603
604 // clear the notification to prevent callbacks to dead client
605 // and reset the player. We assume the player will serialize
606 // access to itself if necessary.
607 if (p != 0) {
608 p->setNotifyCallback(0, 0);
609#if CALLBACK_ANTAGONIZER
610 LOGD("kill Antagonizer");
611 mAntagonizer->kill();
612#endif
613 p->reset();
614 }
615
616 IPCThreadState::self()->flushCommands();
617}
618
619static player_type getPlayerType(int fd, int64_t offset, int64_t length)
620{
621 char buf[20];
622 lseek(fd, offset, SEEK_SET);
623 read(fd, buf, sizeof(buf));
624 lseek(fd, offset, SEEK_SET);
625
626 long ident = *((long*)buf);
627
628 // Ogg vorbis?
629 if (ident == 0x5367674f) // 'OggS'
630 return VORBIS_PLAYER;
631
632 // Some kind of MIDI?
633 EAS_DATA_HANDLE easdata;
634 if (EAS_Init(&easdata) == EAS_SUCCESS) {
635 EAS_FILE locator;
636 locator.path = NULL;
637 locator.fd = fd;
638 locator.offset = offset;
639 locator.length = length;
640 EAS_HANDLE eashandle;
641 if (EAS_OpenFile(easdata, &locator, &eashandle) == EAS_SUCCESS) {
642 EAS_CloseFile(easdata, eashandle);
643 EAS_Shutdown(easdata);
644 return SONIVOX_PLAYER;
645 }
646 EAS_Shutdown(easdata);
647 }
648
Andreas Hubere46b7be2009-07-14 16:56:47 -0700649#if USE_STAGEFRIGHT
650 return STAGEFRIGHT_PLAYER;
651#endif
652
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800653 // Fall through to PV
654 return PV_PLAYER;
655}
656
657static player_type getPlayerType(const char* url)
658{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800659 // use MidiFile for MIDI extensions
660 int lenURL = strlen(url);
661 for (int i = 0; i < NELEM(FILE_EXTS); ++i) {
662 int len = strlen(FILE_EXTS[i].extension);
663 int start = lenURL - len;
664 if (start > 0) {
665 if (!strncmp(url + start, FILE_EXTS[i].extension, len)) {
666 return FILE_EXTS[i].playertype;
667 }
668 }
669 }
670
Andreas Hubere46b7be2009-07-14 16:56:47 -0700671#if USE_STAGEFRIGHT
672 return STAGEFRIGHT_PLAYER;
673#endif
674
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800675 // Fall through to PV
676 return PV_PLAYER;
677}
678
679static sp<MediaPlayerBase> createPlayer(player_type playerType, void* cookie,
680 notify_callback_f notifyFunc)
681{
682 sp<MediaPlayerBase> p;
683 switch (playerType) {
Jean-Baptiste Queru680f8c72009-03-21 11:40:18 -0700684#ifndef NO_OPENCORE
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800685 case PV_PLAYER:
686 LOGV(" create PVPlayer");
687 p = new PVPlayer();
688 break;
Jean-Baptiste Queru680f8c72009-03-21 11:40:18 -0700689#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800690 case SONIVOX_PLAYER:
691 LOGV(" create MidiFile");
692 p = new MidiFile();
693 break;
694 case VORBIS_PLAYER:
695 LOGV(" create VorbisPlayer");
696 p = new VorbisPlayer();
697 break;
Andreas Hubere46b7be2009-07-14 16:56:47 -0700698#if USE_STAGEFRIGHT
699 case STAGEFRIGHT_PLAYER:
700 LOGV(" create StagefrightPlayer");
701 p = new StagefrightPlayer;
702 break;
703#else
704 case STAGEFRIGHT_PLAYER:
705 LOG_ALWAYS_FATAL(
706 "Should not be here, stagefright player not enabled.");
707 break;
708#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800709 }
710 if (p != NULL) {
711 if (p->initCheck() == NO_ERROR) {
712 p->setNotifyCallback(cookie, notifyFunc);
713 } else {
714 p.clear();
715 }
716 }
717 if (p == NULL) {
718 LOGE("Failed to create player object");
719 }
720 return p;
721}
722
723sp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
724{
725 // determine if we have the right player type
726 sp<MediaPlayerBase> p = mPlayer;
727 if ((p != NULL) && (p->playerType() != playerType)) {
728 LOGV("delete player");
729 p.clear();
730 }
731 if (p == NULL) {
732 p = android::createPlayer(playerType, this, notify);
733 }
734 return p;
735}
736
737status_t MediaPlayerService::Client::setDataSource(const char *url)
738{
739 LOGV("setDataSource(%s)", url);
740 if (url == NULL)
741 return UNKNOWN_ERROR;
742
743 if (strncmp(url, "content://", 10) == 0) {
744 // get a filedescriptor for the content Uri and
745 // pass it to the setDataSource(fd) method
746
747 String16 url16(url);
748 int fd = android::openContentProviderFile(url16);
749 if (fd < 0)
750 {
751 LOGE("Couldn't open fd for %s", url);
752 return UNKNOWN_ERROR;
753 }
754 setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
755 close(fd);
756 return mStatus;
757 } else {
758 player_type playerType = getPlayerType(url);
759 LOGV("player type = %d", playerType);
760
761 // create the right type of player
762 sp<MediaPlayerBase> p = createPlayer(playerType);
763 if (p == NULL) return NO_INIT;
764
765 if (!p->hardwareOutput()) {
766 mAudioOutput = new AudioOutput();
767 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
768 }
769
770 // now set data source
771 LOGV(" setDataSource");
772 mStatus = p->setDataSource(url);
773 if (mStatus == NO_ERROR) mPlayer = p;
774 return mStatus;
775 }
776}
777
778status_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
779{
780 LOGV("setDataSource fd=%d, offset=%lld, length=%lld", fd, offset, length);
781 struct stat sb;
782 int ret = fstat(fd, &sb);
783 if (ret != 0) {
784 LOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
785 return UNKNOWN_ERROR;
786 }
787
788 LOGV("st_dev = %llu", sb.st_dev);
789 LOGV("st_mode = %u", sb.st_mode);
790 LOGV("st_uid = %lu", sb.st_uid);
791 LOGV("st_gid = %lu", sb.st_gid);
792 LOGV("st_size = %llu", sb.st_size);
793
794 if (offset >= sb.st_size) {
795 LOGE("offset error");
796 ::close(fd);
797 return UNKNOWN_ERROR;
798 }
799 if (offset + length > sb.st_size) {
800 length = sb.st_size - offset;
801 LOGV("calculated length = %lld", length);
802 }
803
804 player_type playerType = getPlayerType(fd, offset, length);
805 LOGV("player type = %d", playerType);
806
807 // create the right type of player
808 sp<MediaPlayerBase> p = createPlayer(playerType);
809 if (p == NULL) return NO_INIT;
810
811 if (!p->hardwareOutput()) {
812 mAudioOutput = new AudioOutput();
813 static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
814 }
815
816 // now set data source
817 mStatus = p->setDataSource(fd, offset, length);
818 if (mStatus == NO_ERROR) mPlayer = p;
819 return mStatus;
820}
821
822status_t MediaPlayerService::Client::setVideoSurface(const sp<ISurface>& surface)
823{
824 LOGV("[%d] setVideoSurface(%p)", mConnId, surface.get());
825 sp<MediaPlayerBase> p = getPlayer();
826 if (p == 0) return UNKNOWN_ERROR;
827 return p->setVideoSurface(surface);
828}
829
Nicolas Catania20cb94e2009-05-12 23:25:55 -0700830status_t MediaPlayerService::Client::invoke(const Parcel& request,
831 Parcel *reply)
832{
833 sp<MediaPlayerBase> p = getPlayer();
834 if (p == NULL) return UNKNOWN_ERROR;
835 return p->invoke(request, reply);
836}
837
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700838// This call doesn't need to access the native player.
839status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
840{
841 status_t status;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700842 SortedVector<MetadataType> allow, drop;
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700843
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700844 if (unmarshallFilter(filter, &allow, &status) &&
845 unmarshallFilter(filter, &drop, &status)) {
846 Mutex::Autolock lock(mLock);
Nicolas Cataniab2c69392009-07-08 08:57:42 -0700847
848 mMetadataAllow = allow;
849 mMetadataDrop = drop;
850 }
851 return status;
852}
853
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700854status_t MediaPlayerService::Client::getMetadata(
855 bool update_only, bool apply_filter, Parcel *reply)
Nicolas Catania5d55c712009-07-09 09:21:33 -0700856{
857 status_t status;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700858 reply->writeInt32(-1); // Placeholder for the return code
859
860 SortedVector<MetadataType> updates;
861
862 // We don't block notifications while we fetch the data. We clear
863 // mMetadataUpdated first so we don't lose notifications happening
864 // during the rest of this call.
865 {
866 Mutex::Autolock lock(mLock);
867 if (update_only) {
868 updates = mMetadataUpdated;
869 }
870 mMetadataUpdated.clear();
871 }
Nicolas Catania5d55c712009-07-09 09:21:33 -0700872
873 // FIXME: Implement, query the native player and do the optional filtering, etc...
874 status = OK;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700875
Nicolas Catania5d55c712009-07-09 09:21:33 -0700876 return status;
877}
878
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800879status_t MediaPlayerService::Client::prepareAsync()
880{
881 LOGV("[%d] prepareAsync", mConnId);
882 sp<MediaPlayerBase> p = getPlayer();
883 if (p == 0) return UNKNOWN_ERROR;
884 status_t ret = p->prepareAsync();
885#if CALLBACK_ANTAGONIZER
886 LOGD("start Antagonizer");
887 if (ret == NO_ERROR) mAntagonizer->start();
888#endif
889 return ret;
890}
891
892status_t MediaPlayerService::Client::start()
893{
894 LOGV("[%d] start", mConnId);
895 sp<MediaPlayerBase> p = getPlayer();
896 if (p == 0) return UNKNOWN_ERROR;
897 p->setLooping(mLoop);
898 return p->start();
899}
900
901status_t MediaPlayerService::Client::stop()
902{
903 LOGV("[%d] stop", mConnId);
904 sp<MediaPlayerBase> p = getPlayer();
905 if (p == 0) return UNKNOWN_ERROR;
906 return p->stop();
907}
908
909status_t MediaPlayerService::Client::pause()
910{
911 LOGV("[%d] pause", mConnId);
912 sp<MediaPlayerBase> p = getPlayer();
913 if (p == 0) return UNKNOWN_ERROR;
914 return p->pause();
915}
916
917status_t MediaPlayerService::Client::isPlaying(bool* state)
918{
919 *state = false;
920 sp<MediaPlayerBase> p = getPlayer();
921 if (p == 0) return UNKNOWN_ERROR;
922 *state = p->isPlaying();
923 LOGV("[%d] isPlaying: %d", mConnId, *state);
924 return NO_ERROR;
925}
926
927status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
928{
929 LOGV("getCurrentPosition");
930 sp<MediaPlayerBase> p = getPlayer();
931 if (p == 0) return UNKNOWN_ERROR;
932 status_t ret = p->getCurrentPosition(msec);
933 if (ret == NO_ERROR) {
934 LOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
935 } else {
936 LOGE("getCurrentPosition returned %d", ret);
937 }
938 return ret;
939}
940
941status_t MediaPlayerService::Client::getDuration(int *msec)
942{
943 LOGV("getDuration");
944 sp<MediaPlayerBase> p = getPlayer();
945 if (p == 0) return UNKNOWN_ERROR;
946 status_t ret = p->getDuration(msec);
947 if (ret == NO_ERROR) {
948 LOGV("[%d] getDuration = %d", mConnId, *msec);
949 } else {
950 LOGE("getDuration returned %d", ret);
951 }
952 return ret;
953}
954
955status_t MediaPlayerService::Client::seekTo(int msec)
956{
957 LOGV("[%d] seekTo(%d)", mConnId, msec);
958 sp<MediaPlayerBase> p = getPlayer();
959 if (p == 0) return UNKNOWN_ERROR;
960 return p->seekTo(msec);
961}
962
963status_t MediaPlayerService::Client::reset()
964{
965 LOGV("[%d] reset", mConnId);
966 sp<MediaPlayerBase> p = getPlayer();
967 if (p == 0) return UNKNOWN_ERROR;
968 return p->reset();
969}
970
971status_t MediaPlayerService::Client::setAudioStreamType(int type)
972{
973 LOGV("[%d] setAudioStreamType(%d)", mConnId, type);
974 // TODO: for hardware output, call player instead
975 Mutex::Autolock l(mLock);
976 if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
977 return NO_ERROR;
978}
979
980status_t MediaPlayerService::Client::setLooping(int loop)
981{
982 LOGV("[%d] setLooping(%d)", mConnId, loop);
983 mLoop = loop;
984 sp<MediaPlayerBase> p = getPlayer();
985 if (p != 0) return p->setLooping(loop);
986 return NO_ERROR;
987}
988
989status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
990{
991 LOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
992 // TODO: for hardware output, call player instead
993 Mutex::Autolock l(mLock);
994 if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
995 return NO_ERROR;
996}
997
Nicolas Catania4df8b2c2009-07-10 13:53:06 -0700998
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800999void MediaPlayerService::Client::notify(void* cookie, int msg, int ext1, int ext2)
1000{
1001 Client* client = static_cast<Client*>(cookie);
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001002
1003 if (MEDIA_INFO == msg &&
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001004 MEDIA_INFO_METADATA_UPDATE == ext1) {
1005 const MetadataType metadata_type = ext2;
1006
1007 if(client->shouldDropMetadata(metadata_type)) {
1008 return;
1009 }
1010
1011 // Update the list of metadata that have changed. getMetadata
1012 // also access mMetadataUpdated and clears it.
1013 client->addNewMetadataUpdate(metadata_type);
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001014 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001015 LOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
1016 client->mClient->notify(msg, ext1, ext2);
1017}
1018
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001019
1020bool MediaPlayerService::Client::shouldDropMetadata(MetadataType code) const
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001021{
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001022 Mutex::Autolock lock(mLock);
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001023
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001024 if (findMetadata(mMetadataDrop, code)) {
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001025 return true;
1026 }
1027
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001028 if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001029 return false;
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001030 } else {
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001031 return true;
1032 }
1033}
1034
Nicolas Catania4df8b2c2009-07-10 13:53:06 -07001035
1036void MediaPlayerService::Client::addNewMetadataUpdate(MetadataType metadata_type) {
1037 Mutex::Autolock lock(mLock);
1038 if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1039 mMetadataUpdated.add(metadata_type);
1040 }
1041}
1042
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001043#if CALLBACK_ANTAGONIZER
1044const int Antagonizer::interval = 10000; // 10 msecs
1045
1046Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1047 mExit(false), mActive(false), mClient(client), mCb(cb)
1048{
1049 createThread(callbackThread, this);
1050}
1051
1052void Antagonizer::kill()
1053{
1054 Mutex::Autolock _l(mLock);
1055 mActive = false;
1056 mExit = true;
1057 mCondition.wait(mLock);
1058}
1059
1060int Antagonizer::callbackThread(void* user)
1061{
1062 LOGD("Antagonizer started");
1063 Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1064 while (!p->mExit) {
1065 if (p->mActive) {
1066 LOGV("send event");
1067 p->mCb(p->mClient, 0, 0, 0);
1068 }
1069 usleep(interval);
1070 }
1071 Mutex::Autolock _l(p->mLock);
1072 p->mCondition.signal();
1073 LOGD("Antagonizer stopped");
1074 return 0;
1075}
1076#endif
1077
1078static size_t kDefaultHeapSize = 1024 * 1024; // 1MB
1079
1080sp<IMemory> MediaPlayerService::decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1081{
1082 LOGV("decode(%s)", url);
1083 sp<MemoryBase> mem;
1084 sp<MediaPlayerBase> player;
1085
1086 // Protect our precious, precious DRMd ringtones by only allowing
1087 // decoding of http, but not filesystem paths or content Uris.
1088 // If the application wants to decode those, it should open a
1089 // filedescriptor for them and use that.
1090 if (url != NULL && strncmp(url, "http://", 7) != 0) {
1091 LOGD("Can't decode %s by path, use filedescriptor instead", url);
1092 return mem;
1093 }
1094
1095 player_type playerType = getPlayerType(url);
1096 LOGV("player type = %d", playerType);
1097
1098 // create the right type of player
1099 sp<AudioCache> cache = new AudioCache(url);
1100 player = android::createPlayer(playerType, cache.get(), cache->notify);
1101 if (player == NULL) goto Exit;
1102 if (player->hardwareOutput()) goto Exit;
1103
1104 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1105
1106 // set data source
1107 if (player->setDataSource(url) != NO_ERROR) goto Exit;
1108
1109 LOGV("prepare");
1110 player->prepareAsync();
1111
1112 LOGV("wait for prepare");
1113 if (cache->wait() != NO_ERROR) goto Exit;
1114
1115 LOGV("start");
1116 player->start();
1117
1118 LOGV("wait for playback complete");
1119 if (cache->wait() != NO_ERROR) goto Exit;
1120
1121 mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1122 *pSampleRate = cache->sampleRate();
1123 *pNumChannels = cache->channelCount();
1124 *pFormat = cache->format();
1125 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1126
1127Exit:
1128 if (player != 0) player->reset();
1129 return mem;
1130}
1131
1132sp<IMemory> MediaPlayerService::decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
1133{
1134 LOGV("decode(%d, %lld, %lld)", fd, offset, length);
1135 sp<MemoryBase> mem;
1136 sp<MediaPlayerBase> player;
1137
1138 player_type playerType = getPlayerType(fd, offset, length);
1139 LOGV("player type = %d", playerType);
1140
1141 // create the right type of player
1142 sp<AudioCache> cache = new AudioCache("decode_fd");
1143 player = android::createPlayer(playerType, cache.get(), cache->notify);
1144 if (player == NULL) goto Exit;
1145 if (player->hardwareOutput()) goto Exit;
1146
1147 static_cast<MediaPlayerInterface*>(player.get())->setAudioSink(cache);
1148
1149 // set data source
1150 if (player->setDataSource(fd, offset, length) != NO_ERROR) goto Exit;
1151
1152 LOGV("prepare");
1153 player->prepareAsync();
1154
1155 LOGV("wait for prepare");
1156 if (cache->wait() != NO_ERROR) goto Exit;
1157
1158 LOGV("start");
1159 player->start();
1160
1161 LOGV("wait for playback complete");
1162 if (cache->wait() != NO_ERROR) goto Exit;
1163
1164 mem = new MemoryBase(cache->getHeap(), 0, cache->size());
1165 *pSampleRate = cache->sampleRate();
1166 *pNumChannels = cache->channelCount();
1167 *pFormat = cache->format();
1168 LOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
1169
1170Exit:
1171 if (player != 0) player->reset();
1172 ::close(fd);
1173 return mem;
1174}
1175
1176#undef LOG_TAG
1177#define LOG_TAG "AudioSink"
1178MediaPlayerService::AudioOutput::AudioOutput()
Andreas Hubere46b7be2009-07-14 16:56:47 -07001179 : mCallback(NULL),
1180 mCallbackCookie(NULL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001181 mTrack = 0;
1182 mStreamType = AudioSystem::MUSIC;
1183 mLeftVolume = 1.0;
1184 mRightVolume = 1.0;
1185 mLatency = 0;
1186 mMsecsPerFrame = 0;
1187 setMinBufferCount();
1188}
1189
1190MediaPlayerService::AudioOutput::~AudioOutput()
1191{
1192 close();
1193}
1194
1195void MediaPlayerService::AudioOutput::setMinBufferCount()
1196{
1197 char value[PROPERTY_VALUE_MAX];
1198 if (property_get("ro.kernel.qemu", value, 0)) {
1199 mIsOnEmulator = true;
1200 mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator
1201 }
1202}
1203
1204bool MediaPlayerService::AudioOutput::isOnEmulator()
1205{
1206 setMinBufferCount();
1207 return mIsOnEmulator;
1208}
1209
1210int MediaPlayerService::AudioOutput::getMinBufferCount()
1211{
1212 setMinBufferCount();
1213 return mMinBufferCount;
1214}
1215
1216ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1217{
1218 if (mTrack == 0) return NO_INIT;
1219 return mTrack->frameCount() * frameSize();
1220}
1221
1222ssize_t MediaPlayerService::AudioOutput::frameCount() const
1223{
1224 if (mTrack == 0) return NO_INIT;
1225 return mTrack->frameCount();
1226}
1227
1228ssize_t MediaPlayerService::AudioOutput::channelCount() const
1229{
1230 if (mTrack == 0) return NO_INIT;
1231 return mTrack->channelCount();
1232}
1233
1234ssize_t MediaPlayerService::AudioOutput::frameSize() const
1235{
1236 if (mTrack == 0) return NO_INIT;
1237 return mTrack->frameSize();
1238}
1239
1240uint32_t MediaPlayerService::AudioOutput::latency () const
1241{
1242 return mLatency;
1243}
1244
1245float MediaPlayerService::AudioOutput::msecsPerFrame() const
1246{
1247 return mMsecsPerFrame;
1248}
1249
Andreas Hubere46b7be2009-07-14 16:56:47 -07001250status_t MediaPlayerService::AudioOutput::open(
1251 uint32_t sampleRate, int channelCount, int format, int bufferCount,
1252 AudioCallback cb, void *cookie)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001253{
Andreas Hubere46b7be2009-07-14 16:56:47 -07001254 mCallback = cb;
1255 mCallbackCookie = cookie;
1256
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001257 // Check argument "bufferCount" against the mininum buffer count
1258 if (bufferCount < mMinBufferCount) {
1259 LOGD("bufferCount (%d) is too small and increased to %d", bufferCount, mMinBufferCount);
1260 bufferCount = mMinBufferCount;
1261
1262 }
1263 LOGV("open(%u, %d, %d, %d)", sampleRate, channelCount, format, bufferCount);
1264 if (mTrack) close();
1265 int afSampleRate;
1266 int afFrameCount;
1267 int frameCount;
1268
1269 if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1270 return NO_INIT;
1271 }
1272 if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1273 return NO_INIT;
1274 }
1275
1276 frameCount = (sampleRate*afFrameCount*bufferCount)/afSampleRate;
Andreas Hubere46b7be2009-07-14 16:56:47 -07001277
1278 AudioTrack *t;
1279 if (mCallback != NULL) {
1280 t = new AudioTrack(
1281 mStreamType, sampleRate, format, channelCount, frameCount,
1282 0 /* flags */, CallbackWrapper, this);
1283 } else {
1284 t = new AudioTrack(
1285 mStreamType, sampleRate, format, channelCount, frameCount);
1286 }
1287
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001288 if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1289 LOGE("Unable to create audio track");
1290 delete t;
1291 return NO_INIT;
1292 }
1293
1294 LOGV("setVolume");
1295 t->setVolume(mLeftVolume, mRightVolume);
1296 mMsecsPerFrame = 1.e3 / (float) sampleRate;
1297 mLatency = t->latency() + kAudioVideoDelayMs;
1298 mTrack = t;
1299 return NO_ERROR;
1300}
1301
1302void MediaPlayerService::AudioOutput::start()
1303{
1304 LOGV("start");
1305 if (mTrack) {
1306 mTrack->setVolume(mLeftVolume, mRightVolume);
1307 mTrack->start();
1308 }
1309}
1310
1311ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size)
1312{
Andreas Hubere46b7be2009-07-14 16:56:47 -07001313 LOG_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
1314
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001315 //LOGV("write(%p, %u)", buffer, size);
1316 if (mTrack) return mTrack->write(buffer, size);
1317 return NO_INIT;
1318}
1319
1320void MediaPlayerService::AudioOutput::stop()
1321{
1322 LOGV("stop");
1323 if (mTrack) mTrack->stop();
1324}
1325
1326void MediaPlayerService::AudioOutput::flush()
1327{
1328 LOGV("flush");
1329 if (mTrack) mTrack->flush();
1330}
1331
1332void MediaPlayerService::AudioOutput::pause()
1333{
1334 LOGV("pause");
1335 if (mTrack) mTrack->pause();
1336}
1337
1338void MediaPlayerService::AudioOutput::close()
1339{
1340 LOGV("close");
1341 delete mTrack;
1342 mTrack = 0;
1343}
1344
1345void MediaPlayerService::AudioOutput::setVolume(float left, float right)
1346{
1347 LOGV("setVolume(%f, %f)", left, right);
1348 mLeftVolume = left;
1349 mRightVolume = right;
1350 if (mTrack) {
1351 mTrack->setVolume(left, right);
1352 }
1353}
1354
Andreas Hubere46b7be2009-07-14 16:56:47 -07001355// static
1356void MediaPlayerService::AudioOutput::CallbackWrapper(
1357 int event, void *cookie, void *info) {
1358 if (event != AudioTrack::EVENT_MORE_DATA) {
1359 return;
1360 }
1361
1362 AudioOutput *me = (AudioOutput *)cookie;
1363 AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
1364
1365 (*me->mCallback)(
1366 me, buffer->raw, buffer->size, me->mCallbackCookie);
1367}
1368
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001369#undef LOG_TAG
1370#define LOG_TAG "AudioCache"
1371MediaPlayerService::AudioCache::AudioCache(const char* name) :
1372 mChannelCount(0), mFrameCount(1024), mSampleRate(0), mSize(0),
1373 mError(NO_ERROR), mCommandComplete(false)
1374{
1375 // create ashmem heap
1376 mHeap = new MemoryHeapBase(kDefaultHeapSize, 0, name);
1377}
1378
1379uint32_t MediaPlayerService::AudioCache::latency () const
1380{
1381 return 0;
1382}
1383
1384float MediaPlayerService::AudioCache::msecsPerFrame() const
1385{
1386 return mMsecsPerFrame;
1387}
1388
Andreas Hubere46b7be2009-07-14 16:56:47 -07001389status_t MediaPlayerService::AudioCache::open(
1390 uint32_t sampleRate, int channelCount, int format, int bufferCount,
1391 AudioCallback cb, void *cookie)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001392{
Andreas Hubere46b7be2009-07-14 16:56:47 -07001393 if (cb != NULL) {
1394 return UNKNOWN_ERROR; // TODO: implement this.
1395 }
1396
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001397 LOGV("open(%u, %d, %d, %d)", sampleRate, channelCount, format, bufferCount);
1398 if (mHeap->getHeapID() < 0) return NO_INIT;
1399 mSampleRate = sampleRate;
1400 mChannelCount = (uint16_t)channelCount;
1401 mFormat = (uint16_t)format;
1402 mMsecsPerFrame = 1.e3 / (float) sampleRate;
1403 return NO_ERROR;
1404}
1405
1406ssize_t MediaPlayerService::AudioCache::write(const void* buffer, size_t size)
1407{
1408 LOGV("write(%p, %u)", buffer, size);
1409 if ((buffer == 0) || (size == 0)) return size;
1410
1411 uint8_t* p = static_cast<uint8_t*>(mHeap->getBase());
1412 if (p == NULL) return NO_INIT;
1413 p += mSize;
1414 LOGV("memcpy(%p, %p, %u)", p, buffer, size);
1415 if (mSize + size > mHeap->getSize()) {
1416 LOGE("Heap size overflow! req size: %d, max size: %d", (mSize + size), mHeap->getSize());
1417 size = mHeap->getSize() - mSize;
1418 }
1419 memcpy(p, buffer, size);
1420 mSize += size;
1421 return size;
1422}
1423
1424// call with lock held
1425status_t MediaPlayerService::AudioCache::wait()
1426{
1427 Mutex::Autolock lock(mLock);
1428 if (!mCommandComplete) {
1429 mSignal.wait(mLock);
1430 }
1431 mCommandComplete = false;
1432
1433 if (mError == NO_ERROR) {
1434 LOGV("wait - success");
1435 } else {
1436 LOGV("wait - error");
1437 }
1438 return mError;
1439}
1440
1441void MediaPlayerService::AudioCache::notify(void* cookie, int msg, int ext1, int ext2)
1442{
1443 LOGV("notify(%p, %d, %d, %d)", cookie, msg, ext1, ext2);
1444 AudioCache* p = static_cast<AudioCache*>(cookie);
1445
1446 // ignore buffering messages
1447 if (msg == MEDIA_BUFFERING_UPDATE) return;
1448
1449 // set error condition
1450 if (msg == MEDIA_ERROR) {
1451 LOGE("Error %d, %d occurred", ext1, ext2);
1452 p->mError = ext1;
1453 }
1454
1455 // wake up thread
1456 LOGV("wakeup thread");
1457 p->mCommandComplete = true;
1458 p->mSignal.signal();
1459}
1460
1461}; // namespace android