MediaPlayerService.cpp revision 99f31604136d66ae10e20669fb6b5716f342bde0
108fa40c5cb5229b7969b2a5146855a337870f45aJim Miller/*
208fa40c5cb5229b7969b2a5146855a337870f45aJim Miller**
308fa40c5cb5229b7969b2a5146855a337870f45aJim Miller** Copyright 2008, The Android Open Source Project
408fa40c5cb5229b7969b2a5146855a337870f45aJim Miller**
508fa40c5cb5229b7969b2a5146855a337870f45aJim Miller** Licensed under the Apache License, Version 2.0 (the "License");
608fa40c5cb5229b7969b2a5146855a337870f45aJim Miller** you may not use this file except in compliance with the License.
708fa40c5cb5229b7969b2a5146855a337870f45aJim Miller** You may obtain a copy of the License at
808fa40c5cb5229b7969b2a5146855a337870f45aJim Miller**
908fa40c5cb5229b7969b2a5146855a337870f45aJim Miller**     http://www.apache.org/licenses/LICENSE-2.0
1008fa40c5cb5229b7969b2a5146855a337870f45aJim Miller**
1108fa40c5cb5229b7969b2a5146855a337870f45aJim Miller** Unless required by applicable law or agreed to in writing, software
1208fa40c5cb5229b7969b2a5146855a337870f45aJim Miller** distributed under the License is distributed on an "AS IS" BASIS,
1308fa40c5cb5229b7969b2a5146855a337870f45aJim Miller** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1408fa40c5cb5229b7969b2a5146855a337870f45aJim Miller** See the License for the specific language governing permissions and
1508fa40c5cb5229b7969b2a5146855a337870f45aJim Miller** limitations under the License.
1608fa40c5cb5229b7969b2a5146855a337870f45aJim Miller*/
17ebbf205bc6e8292f74d8fc4652c70274a445f907Jim Miller
1808fa40c5cb5229b7969b2a5146855a337870f45aJim Miller// Proxy for media player implementations
19ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller
20ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller//#define LOG_NDEBUG 0
2108fa40c5cb5229b7969b2a5146855a337870f45aJim Miller#define LOG_TAG "MediaPlayerService"
22d08c2aceb238b02d8348518a2c87693054c6ce37Jim Miller#include <utils/Log.h>
2308fa40c5cb5229b7969b2a5146855a337870f45aJim Miller
24a7596147b43940cad3f76c53ed154ef088b9269bJim Miller#include <sys/types.h>
259f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller#include <sys/stat.h>
26ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller#include <sys/time.h>
2708fa40c5cb5229b7969b2a5146855a337870f45aJim Miller#include <dirent.h>
2808fa40c5cb5229b7969b2a5146855a337870f45aJim Miller#include <unistd.h>
299f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller
309f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller#include <string.h>
3108fa40c5cb5229b7969b2a5146855a337870f45aJim Miller
3208fa40c5cb5229b7969b2a5146855a337870f45aJim Miller#include <cutils/atomic.h>
33d08c2aceb238b02d8348518a2c87693054c6ce37Jim Miller#include <cutils/properties.h> // for property_get
34ebbf205bc6e8292f74d8fc4652c70274a445f907Jim Miller
35ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller#include <utils/misc.h>
3608fa40c5cb5229b7969b2a5146855a337870f45aJim Miller
37a7596147b43940cad3f76c53ed154ef088b9269bJim Miller#include <binder/IBatteryStats.h>
3808fa40c5cb5229b7969b2a5146855a337870f45aJim Miller#include <binder/IPCThreadState.h>
399f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller#include <binder/IServiceManager.h>
40ba67aee02cf864793129976cd8a8a46e60c60577Jim Miller#include <binder/MemoryHeapBase.h>
419f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller#include <binder/MemoryBase.h>
42ba67aee02cf864793129976cd8a8a46e60c60577Jim Miller#include <gui/Surface.h>
43ba67aee02cf864793129976cd8a8a46e60c60577Jim Miller#include <utils/Errors.h>  // for status_t
449f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller#include <utils/String8.h>
459f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller#include <utils/SystemClock.h>
4608fa40c5cb5229b7969b2a5146855a337870f45aJim Miller#include <utils/Timers.h>
4708fa40c5cb5229b7969b2a5146855a337870f45aJim Miller#include <utils/Vector.h>
48ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller
49ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller#include <media/IMediaHTTPService.h>
50ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller#include <media/IRemoteDisplay.h>
51ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller#include <media/IRemoteDisplayClient.h>
5208fa40c5cb5229b7969b2a5146855a337870f45aJim Miller#include <media/MediaPlayerInterface.h>
5308fa40c5cb5229b7969b2a5146855a337870f45aJim Miller#include <media/mediarecorder.h>
5408fa40c5cb5229b7969b2a5146855a337870f45aJim Miller#include <media/MediaMetadataRetrieverInterface.h>
5508fa40c5cb5229b7969b2a5146855a337870f45aJim Miller#include <media/Metadata.h>
56d08c2aceb238b02d8348518a2c87693054c6ce37Jim Miller#include <media/AudioTrack.h>
5708fa40c5cb5229b7969b2a5146855a337870f45aJim Miller#include <media/MemoryLeakTrackUtil.h>
58a7596147b43940cad3f76c53ed154ef088b9269bJim Miller#include <media/stagefright/MediaCodecList.h>
59fe6439f02db3a541d77a7afb27e3bca1ae7493edJim Miller#include <media/stagefright/MediaErrors.h>
60a7596147b43940cad3f76c53ed154ef088b9269bJim Miller#include <media/stagefright/AudioPlayer.h>
61a7596147b43940cad3f76c53ed154ef088b9269bJim Miller#include <media/stagefright/foundation/ADebug.h>
6208fa40c5cb5229b7969b2a5146855a337870f45aJim Miller#include <media/stagefright/foundation/ALooperRoster.h>
63ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller
64ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller#include <system/audio.h>
65ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller
66ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller#include <private/android_filesystem_config.h>
6708fa40c5cb5229b7969b2a5146855a337870f45aJim Miller
68ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller#include "ActivityManager.h"
69ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller#include "MediaRecorderClient.h"
70ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller#include "MediaPlayerService.h"
7108fa40c5cb5229b7969b2a5146855a337870f45aJim Miller#include "MetadataRetrieverClient.h"
72ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller#include "MediaPlayerFactory.h"
73ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller
74ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller#include "TestPlayerStub.h"
75ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller#include "StagefrightPlayer.h"
76a7596147b43940cad3f76c53ed154ef088b9269bJim Miller#include "nuplayer/NuPlayerDriver.h"
77ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller
78ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller#include <OMX.h>
79ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller
80ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller#include "Crypto.h"
81ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller#include "Drm.h"
82ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller#include "HDCP.h"
8308fa40c5cb5229b7969b2a5146855a337870f45aJim Miller#include "HTTPBase.h"
84ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller#include "RemoteDisplay.h"
85ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller
86ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Millernamespace {
87ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Millerusing android::media::Metadata;
88ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Millerusing android::status_t;
8908fa40c5cb5229b7969b2a5146855a337870f45aJim Millerusing android::OK;
90ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Millerusing android::BAD_VALUE;
91ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Millerusing android::NOT_ENOUGH_DATA;
92ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Millerusing android::Parcel;
93ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller
94ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller// Max number of entries in the filter.
95ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Millerconst int kMaxFilterSize = 64;  // I pulled that out of thin air.
969f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller
97ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller// FIXME: Move all the metadata related function in the Metadata.cpp
98ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller
99ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller
100ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller// Unmarshall a filter from a Parcel.
101ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller// Filter format in a parcel:
102ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller//
103ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller//  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
104ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
105ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller// |                       number of entries (n)                   |
106fe6439f02db3a541d77a7afb27e3bca1ae7493edJim Miller// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
107fe6439f02db3a541d77a7afb27e3bca1ae7493edJim Miller// |                       metadata type 1                         |
108fe6439f02db3a541d77a7afb27e3bca1ae7493edJim Miller// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
109fe6439f02db3a541d77a7afb27e3bca1ae7493edJim Miller// |                       metadata type 2                         |
110fe6439f02db3a541d77a7afb27e3bca1ae7493edJim Miller// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
111ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller//  ....
112ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
113ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller// |                       metadata type n                         |
114ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1159f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller//
11608fa40c5cb5229b7969b2a5146855a337870f45aJim Miller// @param p Parcel that should start with a filter.
117ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller// @param[out] filter On exit contains the list of metadata type to be
118ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller//                    filtered.
119ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller// @param[out] status On exit contains the status code to be returned.
120ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller// @return true if the parcel starts with a valid filter.
121ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Millerbool unmarshallFilter(const Parcel& p,
122ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller                      Metadata::Filter *filter,
123ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller                      status_t *status)
124a7596147b43940cad3f76c53ed154ef088b9269bJim Miller{
125ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    int32_t val;
126ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    if (p.readInt32(&val) != OK)
127ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    {
128ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        ALOGE("Failed to read filter's length");
129ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        *status = NOT_ENOUGH_DATA;
130a7596147b43940cad3f76c53ed154ef088b9269bJim Miller        return false;
131ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    }
132ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller
133ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    if( val > kMaxFilterSize || val < 0)
134ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    {
135ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        ALOGE("Invalid filter len %d", val);
136a7596147b43940cad3f76c53ed154ef088b9269bJim Miller        *status = BAD_VALUE;
137ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        return false;
138ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    }
139ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller
140ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    const size_t num = val;
141ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller
142ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    filter->clear();
143ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    filter->setCapacity(num);
144ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller
1459f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    size_t size = num * sizeof(Metadata::Type);
146ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller
147ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller
148ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    if (p.dataAvail() < size)
149ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    {
150ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        ALOGE("Filter too short expected %d but got %d", size, p.dataAvail());
1519f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller        *status = NOT_ENOUGH_DATA;
152ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        return false;
153ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    }
154ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller
155ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    const Metadata::Type *data =
156ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller            static_cast<const Metadata::Type*>(p.readInplace(size));
157ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller
158ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    if (NULL == data)
1599f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    {
160ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        ALOGE("Filter had no data");
161ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        *status = BAD_VALUE;
162ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        return false;
163ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    }
164ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller
1659f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    // TODO: The stl impl of vector would be more efficient here
166a7596147b43940cad3f76c53ed154ef088b9269bJim Miller    // because it degenerates into a memcpy on pod types. Try to
16708fa40c5cb5229b7969b2a5146855a337870f45aJim Miller    // replace later or use stl::set.
168d08c2aceb238b02d8348518a2c87693054c6ce37Jim Miller    for (size_t i = 0; i < num; ++i)
169a7596147b43940cad3f76c53ed154ef088b9269bJim Miller    {
1709f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller        filter->add(*data);
1719f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller        ++data;
1729f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    }
1739f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    *status = OK;
1749f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    return true;
175ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller}
176ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller
177ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller// @param filter Of metadata type.
178ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller// @param val To be searched.
179fe6439f02db3a541d77a7afb27e3bca1ae7493edJim Miller// @return true if a match was found.
180ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Millerbool findMetadata(const Metadata::Filter& filter, const int32_t val)
181ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller{
182ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    // Deal with empty and ANY right away
183ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    if (filter.isEmpty()) return false;
184ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    if (filter[0] == Metadata::kAny) return true;
185ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller
186ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    return filter.indexOf(val) >= 0;
187ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller}
188ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller
189ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller}  // anonymous namespace
190ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller
191ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller
192ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Millernamespace {
193ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Millerusing android::Parcel;
194ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Millerusing android::String16;
19508fa40c5cb5229b7969b2a5146855a337870f45aJim Miller
1969f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller// marshalling tag indicating flattened utf16 tags
197ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller// keep in sync with frameworks/base/media/java/android/media/AudioAttributes.java
198ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Millerconst int32_t kAudioAttributesMarshallTagFlattenTags = 1;
1999f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller
2009f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller// Audio attributes format in a parcel:
201ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller//
202ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller//  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
203ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
204ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller// |                       usage                                   |
205ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
206ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller// |                       content_type                            |
207ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
208ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller// |                       source                                  |
209ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
210ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller// |                       flags                                   |
211ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
212ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller// |                       kAudioAttributesMarshallTagFlattenTags  | // ignore tags if not found
213ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
214ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller// |                       flattened tags in UTF16                 |
215ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller// |                         ...                                   |
216ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
217ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller//
218ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller// @param p Parcel that contains audio attributes.
219ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller// @param[out] attributes On exit points to an initialized audio_attributes_t structure
220ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller// @param[out] status On exit contains the status code to be returned.
221ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Millervoid unmarshallAudioAttributes(const Parcel& parcel, audio_attributes_t *attributes)
222ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller{
223ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    attributes->usage = (audio_usage_t) parcel.readInt32();
224ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    attributes->content_type = (audio_content_type_t) parcel.readInt32();
225ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    attributes->source = (audio_source_t) parcel.readInt32();
226ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    attributes->flags = (audio_flags_mask_t) parcel.readInt32();
227ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    const bool hasFlattenedTag = (parcel.readInt32() == kAudioAttributesMarshallTagFlattenTags);
228ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    if (hasFlattenedTag) {
229ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        // the tags are UTF16, convert to UTF8
230ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        String16 tags = parcel.readString16();
231ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        ssize_t realTagSize = utf16_to_utf8_length(tags.string(), tags.size());
232ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        if (realTagSize <= 0) {
233ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller            strcpy(attributes->tags, "");
234ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        } else {
235ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller            // copy the flattened string into the attributes as the destination for the conversion:
236ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller            // copying array size -1, array for tags was calloc'd, no need to NULL-terminate it
237ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller            size_t tagSize = realTagSize > AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 ?
238ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller                    AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 : realTagSize;
23908fa40c5cb5229b7969b2a5146855a337870f45aJim Miller            utf16_to_utf8(tags.string(), tagSize, attributes->tags);
24008fa40c5cb5229b7969b2a5146855a337870f45aJim Miller        }
2419f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    } else {
2429f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller        ALOGE("unmarshallAudioAttributes() received unflattened tags, ignoring tag values");
243ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        strcpy(attributes->tags, "");
2449f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    }
2459f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller}
2469f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller} // anonymous namespace
2479f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller
2489f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller
2499f0753f5a378fc80da86305b33244acc6fc53f01Jim Millernamespace android {
2509f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller
2519f0753f5a378fc80da86305b33244acc6fc53f01Jim Millerextern ALooperRoster gLooperRoster;
252ba67aee02cf864793129976cd8a8a46e60c60577Jim Miller
2539f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller
2549f0753f5a378fc80da86305b33244acc6fc53f01Jim Millerstatic bool checkPermission(const char* permissionString) {
2559f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller#ifndef HAVE_ANDROID_OS
2569f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    return true;
257ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller#endif
2589f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
2599f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    bool ok = checkCallingPermission(String16(permissionString));
2609f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    if (!ok) ALOGE("Request requires %s", permissionString);
2619f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    return ok;
262ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller}
263ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller
264ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller// TODO: Find real cause of Audio/Video delay in PV framework and remove this workaround
2659f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller/* static */ int MediaPlayerService::AudioOutput::mMinBufferCount = 4;
2669f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller/* static */ bool MediaPlayerService::AudioOutput::mIsOnEmulator = false;
2679f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller
2689f0753f5a378fc80da86305b33244acc6fc53f01Jim Millervoid MediaPlayerService::instantiate() {
269ba67aee02cf864793129976cd8a8a46e60c60577Jim Miller    defaultServiceManager()->addService(
27006e658f324a937bec1c5ddbe9c3100c3d2fec371Jim Miller            String16("media.player"), new MediaPlayerService());
2719f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller}
272ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller
273ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim MillerMediaPlayerService::MediaPlayerService()
274ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller{
275ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    ALOGV("MediaPlayerService created");
27606e658f324a937bec1c5ddbe9c3100c3d2fec371Jim Miller    mNextConnId = 1;
2779f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller
2789f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    mBatteryAudio.refCount = 0;
2799f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2809f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller        mBatteryAudio.deviceOn[i] = 0;
281ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        mBatteryAudio.lastTime[i] = 0;
282ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        mBatteryAudio.totalTime[i] = 0;
2839f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    }
284ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    // speaker is on by default
28508fa40c5cb5229b7969b2a5146855a337870f45aJim Miller    mBatteryAudio.deviceOn[SPEAKER] = 1;
2869f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller
287ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    // reset battery stats
2889f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    // if the mediaserver has crashed, battery stats could be left
2899f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    // in bad state, reset the state upon service start.
290ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    const sp<IServiceManager> sm(defaultServiceManager());
291ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    if (sm != NULL) {
2929f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller        const String16 name("batterystats");
293ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        // use checkService() to avoid blocking if service is not up yet
29408fa40c5cb5229b7969b2a5146855a337870f45aJim Miller        sp<IBatteryStats> batteryStats =
2959f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller                interface_cast<IBatteryStats>(sm->checkService(name));
2969f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller        if (batteryStats != NULL) {
297ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller            batteryStats->noteResetVideo();
2989f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller            batteryStats->noteResetAudio();
299ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        }
300ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    }
301ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller
302ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    MediaPlayerFactory::registerBuiltinFactories();
303ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller}
304ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller
3059f0753f5a378fc80da86305b33244acc6fc53f01Jim MillerMediaPlayerService::~MediaPlayerService()
30608fa40c5cb5229b7969b2a5146855a337870f45aJim Miller{
3079f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    ALOGV("MediaPlayerService destroyed");
3089f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller}
3099f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller
3109f0753f5a378fc80da86305b33244acc6fc53f01Jim Millersp<IMediaRecorder> MediaPlayerService::createMediaRecorder()
311ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller{
312ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    pid_t pid = IPCThreadState::self()->getCallingPid();
313ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    sp<MediaRecorderClient> recorder = new MediaRecorderClient(this, pid);
3149f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    wp<MediaRecorderClient> w = recorder;
3159f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    Mutex::Autolock lock(mLock);
3169f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    mMediaRecorderClients.add(w);
3179f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    ALOGV("Create new media recorder client from pid %d", pid);
3189f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    return recorder;
319ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller}
320ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller
3219f0753f5a378fc80da86305b33244acc6fc53f01Jim Millervoid MediaPlayerService::removeMediaRecorderClient(wp<MediaRecorderClient> client)
322ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller{
323a7596147b43940cad3f76c53ed154ef088b9269bJim Miller    Mutex::Autolock lock(mLock);
3249f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    mMediaRecorderClients.remove(client);
325ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    ALOGV("Delete media recorder client");
3269f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller}
3279f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller
3289f0753f5a378fc80da86305b33244acc6fc53f01Jim Millersp<IMediaMetadataRetriever> MediaPlayerService::createMetadataRetriever()
329ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller{
330ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    pid_t pid = IPCThreadState::self()->getCallingPid();
3319f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    sp<MetadataRetrieverClient> retriever = new MetadataRetrieverClient(pid);
332ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    ALOGV("Create new media retriever from pid %d", pid);
33308fa40c5cb5229b7969b2a5146855a337870f45aJim Miller    return retriever;
3349f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller}
3359f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller
336ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Millersp<IMediaPlayer> MediaPlayerService::create(const sp<IMediaPlayerClient>& client,
3379f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller        int audioSessionId)
338ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller{
3399f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    pid_t pid = IPCThreadState::self()->getCallingPid();
340ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    int32_t connId = android_atomic_inc(&mNextConnId);
3419f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller
34208fa40c5cb5229b7969b2a5146855a337870f45aJim Miller    sp<Client> c = new Client(
3439f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller            this, pid, connId, client, audioSessionId,
3449f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller            IPCThreadState::self()->getCallingUid());
3459f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller
3469f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    ALOGV("Create new client(%d) from pid %d, uid %d, ", connId, pid,
3479f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller         IPCThreadState::self()->getCallingUid());
348ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller
349ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    wp<Client> w = c;
3509f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    {
3519f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller        Mutex::Autolock lock(mLock);
3529f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller        mClients.add(w);
3539f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    }
354ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    return c;
355ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller}
356ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller
3579f0753f5a378fc80da86305b33244acc6fc53f01Jim Millersp<IMediaCodecList> MediaPlayerService::getCodecList() const {
358ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    return MediaCodecList::getLocalInstance();
3599f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller}
3609f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller
3619f0753f5a378fc80da86305b33244acc6fc53f01Jim Millersp<IOMX> MediaPlayerService::getOMX() {
3629f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    Mutex::Autolock autoLock(mLock);
3639f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller
364ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    if (mOMX.get() == NULL) {
36508fa40c5cb5229b7969b2a5146855a337870f45aJim Miller        mOMX = new OMX;
36608fa40c5cb5229b7969b2a5146855a337870f45aJim Miller    }
36708fa40c5cb5229b7969b2a5146855a337870f45aJim Miller
368ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    return mOMX;
369ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller}
3709f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller
3719f0753f5a378fc80da86305b33244acc6fc53f01Jim Millersp<ICrypto> MediaPlayerService::makeCrypto() {
3729f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    return new Crypto;
3739f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller}
374d08c2aceb238b02d8348518a2c87693054c6ce37Jim Miller
3759f0753f5a378fc80da86305b33244acc6fc53f01Jim Millersp<IDrm> MediaPlayerService::makeDrm() {
3769f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    return new Drm;
377ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller}
378ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller
379d08c2aceb238b02d8348518a2c87693054c6ce37Jim Millersp<IHDCP> MediaPlayerService::makeHDCP(bool createEncryptionModule) {
380ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    return new HDCP(createEncryptionModule);
381ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller}
382ccdfa93f609d3f306a35902df323939e266a7ab3Jorim Jaggi
383ccdfa93f609d3f306a35902df323939e266a7ab3Jorim Jaggisp<IRemoteDisplay> MediaPlayerService::listenForRemoteDisplay(
384ccdfa93f609d3f306a35902df323939e266a7ab3Jorim Jaggi        const sp<IRemoteDisplayClient>& client, const String8& iface) {
385ccdfa93f609d3f306a35902df323939e266a7ab3Jorim Jaggi    if (!checkPermission("android.permission.CONTROL_WIFI_DISPLAY")) {
386ccdfa93f609d3f306a35902df323939e266a7ab3Jorim Jaggi        return NULL;
387ccdfa93f609d3f306a35902df323939e266a7ab3Jorim Jaggi    }
388ccdfa93f609d3f306a35902df323939e266a7ab3Jorim Jaggi
389ccdfa93f609d3f306a35902df323939e266a7ab3Jorim Jaggi    return new RemoteDisplay(client, iface.string());
390ccdfa93f609d3f306a35902df323939e266a7ab3Jorim Jaggi}
391ccdfa93f609d3f306a35902df323939e266a7ab3Jorim Jaggi
392ccdfa93f609d3f306a35902df323939e266a7ab3Jorim Jaggistatus_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
393ccdfa93f609d3f306a35902df323939e266a7ab3Jorim Jaggi{
394ccdfa93f609d3f306a35902df323939e266a7ab3Jorim Jaggi    const size_t SIZE = 256;
395ccdfa93f609d3f306a35902df323939e266a7ab3Jorim Jaggi    char buffer[SIZE];
396ccdfa93f609d3f306a35902df323939e266a7ab3Jorim Jaggi    String8 result;
397ccdfa93f609d3f306a35902df323939e266a7ab3Jorim Jaggi
398ccdfa93f609d3f306a35902df323939e266a7ab3Jorim Jaggi    result.append(" AudioOutput\n");
399ccdfa93f609d3f306a35902df323939e266a7ab3Jorim Jaggi    snprintf(buffer, 255, "  stream type(%d), left - right volume(%f, %f)\n",
400ccdfa93f609d3f306a35902df323939e266a7ab3Jorim Jaggi            mStreamType, mLeftVolume, mRightVolume);
401ccdfa93f609d3f306a35902df323939e266a7ab3Jorim Jaggi    result.append(buffer);
4029f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    snprintf(buffer, 255, "  msec per frame(%f), latency (%d)\n",
4039f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller            mMsecsPerFrame, (mTrack != 0) ? mTrack->latency() : -1);
4049f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    result.append(buffer);
4059f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    snprintf(buffer, 255, "  aux effect id(%d), send level (%f)\n",
406ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller            mAuxEffectId, mSendLevel);
407ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    result.append(buffer);
408ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller
409ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    ::write(fd, result.string(), result.size());
410ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    if (mTrack != 0) {
411ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        mTrack->dump(fd, args);
412ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    }
413ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    return NO_ERROR;
4149f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller}
4159f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller
4169f0753f5a378fc80da86305b33244acc6fc53f01Jim Millerstatus_t MediaPlayerService::Client::dump(int fd, const Vector<String16>& args) const
4179f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller{
418ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    const size_t SIZE = 256;
419ccdfa93f609d3f306a35902df323939e266a7ab3Jorim Jaggi    char buffer[SIZE];
4209f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    String8 result;
421ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    result.append(" Client\n");
422ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    snprintf(buffer, 255, "  pid(%d), connId(%d), status(%d), looping(%s)\n",
423ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller            mPid, mConnId, mStatus, mLoop?"true": "false");
424ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    result.append(buffer);
425ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    write(fd, result.string(), result.size());
426ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    if (mPlayer != NULL) {
427ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        mPlayer->dump(fd, args);
4289f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    }
429d08c2aceb238b02d8348518a2c87693054c6ce37Jim Miller    if (mAudioOutput != 0) {
430d08c2aceb238b02d8348518a2c87693054c6ce37Jim Miller        mAudioOutput->dump(fd, args);
431d08c2aceb238b02d8348518a2c87693054c6ce37Jim Miller    }
4329f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    write(fd, "\n", 1);
4339f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    return NO_ERROR;
4349f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller}
4359f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller
4369f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller/**
4379f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller * The only arguments this understands right now are -c, -von and -voff,
4389f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller * which are parsed by ALooperRoster::dump()
439fe6439f02db3a541d77a7afb27e3bca1ae7493edJim Miller */
440fe6439f02db3a541d77a7afb27e3bca1ae7493edJim Millerstatus_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
4419f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller{
442ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    const size_t SIZE = 256;
4439f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    char buffer[SIZE];
444ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    String8 result;
44508fa40c5cb5229b7969b2a5146855a337870f45aJim Miller    SortedVector< sp<Client> > clients; //to serialise the mutex unlock & client destruction.
446fe6439f02db3a541d77a7afb27e3bca1ae7493edJim Miller    SortedVector< sp<MediaRecorderClient> > mediaRecorderClients;
447ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller
4489f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
4499f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller        snprintf(buffer, SIZE, "Permission Denial: "
45008fa40c5cb5229b7969b2a5146855a337870f45aJim Miller                "can't dump MediaPlayerService from pid=%d, uid=%d\n",
4519f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller                IPCThreadState::self()->getCallingPid(),
452ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller                IPCThreadState::self()->getCallingUid());
453ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        result.append(buffer);
454ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    } else {
455ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        Mutex::Autolock lock(mLock);
456ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        for (int i = 0, n = mClients.size(); i < n; ++i) {
457fe6439f02db3a541d77a7afb27e3bca1ae7493edJim Miller            sp<Client> c = mClients[i].promote();
458ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller            if (c != 0) c->dump(fd, args);
459ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller            clients.add(c);
4609f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller        }
46108fa40c5cb5229b7969b2a5146855a337870f45aJim Miller        if (mMediaRecorderClients.size() == 0) {
4629f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller                result.append(" No media recorder client\n\n");
463fe6439f02db3a541d77a7afb27e3bca1ae7493edJim Miller        } else {
464ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller            for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) {
465ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller                sp<MediaRecorderClient> c = mMediaRecorderClients[i].promote();
466ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller                if (c != 0) {
467ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller                    snprintf(buffer, 255, " MediaRecorderClient pid(%d)\n", c->mPid);
468ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller                    result.append(buffer);
469ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller                    write(fd, result.string(), result.size());
470ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller                    result = "\n";
471ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller                    c->dump(fd, args);
472ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller                    mediaRecorderClients.add(c);
473ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller                }
474ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller            }
475ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        }
476ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller
477ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        result.append(" Files opened and/or mapped:\n");
478ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        snprintf(buffer, SIZE, "/proc/%d/maps", getpid());
479ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        FILE *f = fopen(buffer, "r");
480ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        if (f) {
481ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller            while (!feof(f)) {
482ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller                fgets(buffer, SIZE, f);
483ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller                if (strstr(buffer, " /storage/") ||
48408fa40c5cb5229b7969b2a5146855a337870f45aJim Miller                    strstr(buffer, " /system/sounds/") ||
485ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller                    strstr(buffer, " /data/") ||
48608fa40c5cb5229b7969b2a5146855a337870f45aJim Miller                    strstr(buffer, " /system/media/")) {
487ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller                    result.append("  ");
48808fa40c5cb5229b7969b2a5146855a337870f45aJim Miller                    result.append(buffer);
48908fa40c5cb5229b7969b2a5146855a337870f45aJim Miller                }
49008fa40c5cb5229b7969b2a5146855a337870f45aJim Miller            }
4919f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller            fclose(f);
4929f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller        } else {
4939f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller            result.append("couldn't open ");
494ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller            result.append(buffer);
495ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller            result.append("\n");
4969f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller        }
49708fa40c5cb5229b7969b2a5146855a337870f45aJim Miller
4989f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller        snprintf(buffer, SIZE, "/proc/%d/fd", getpid());
4999f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller        DIR *d = opendir(buffer);
5009f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller        if (d) {
5019f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller            struct dirent *ent;
502ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller            while((ent = readdir(d)) != NULL) {
5039f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller                if (strcmp(ent->d_name,".") && strcmp(ent->d_name,"..")) {
504ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller                    snprintf(buffer, SIZE, "/proc/%d/fd/%s", getpid(), ent->d_name);
505ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller                    struct stat s;
506ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller                    if (lstat(buffer, &s) == 0) {
507ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller                        if ((s.st_mode & S_IFMT) == S_IFLNK) {
508ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller                            char linkto[256];
50908fa40c5cb5229b7969b2a5146855a337870f45aJim Miller                            int len = readlink(buffer, linkto, sizeof(linkto));
51008fa40c5cb5229b7969b2a5146855a337870f45aJim Miller                            if(len > 0) {
51108fa40c5cb5229b7969b2a5146855a337870f45aJim Miller                                if(len > 255) {
51208fa40c5cb5229b7969b2a5146855a337870f45aJim Miller                                    linkto[252] = '.';
5139f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller                                    linkto[253] = '.';
5149f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller                                    linkto[254] = '.';
5159f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller                                    linkto[255] = 0;
516ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller                                } else {
5179f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller                                    linkto[len] = 0;
51808fa40c5cb5229b7969b2a5146855a337870f45aJim Miller                                }
5199f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller                                if (strstr(linkto, "/storage/") == linkto ||
5209f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller                                    strstr(linkto, "/system/sounds/") == linkto ||
52108fa40c5cb5229b7969b2a5146855a337870f45aJim Miller                                    strstr(linkto, "/data/") == linkto ||
52208fa40c5cb5229b7969b2a5146855a337870f45aJim Miller                                    strstr(linkto, "/system/media/") == linkto) {
5239f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller                                    result.append("  ");
52408fa40c5cb5229b7969b2a5146855a337870f45aJim Miller                                    result.append(buffer);
5259f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller                                    result.append(" -> ");
52608fa40c5cb5229b7969b2a5146855a337870f45aJim Miller                                    result.append(linkto);
527a7596147b43940cad3f76c53ed154ef088b9269bJim Miller                                    result.append("\n");
5289f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller                                }
52908fa40c5cb5229b7969b2a5146855a337870f45aJim Miller                            }
53008fa40c5cb5229b7969b2a5146855a337870f45aJim Miller                        } else {
53108fa40c5cb5229b7969b2a5146855a337870f45aJim Miller                            result.append("  unexpected type for ");
5329f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller                            result.append(buffer);
5339f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller                            result.append("\n");
5349f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller                        }
535ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller                    }
536ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller                }
5379f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller            }
5389f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller            closedir(d);
5399f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller        } else {
5409f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller            result.append("couldn't open ");
54108fa40c5cb5229b7969b2a5146855a337870f45aJim Miller            result.append(buffer);
5429f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller            result.append("\n");
54308fa40c5cb5229b7969b2a5146855a337870f45aJim Miller        }
5449f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller
54508fa40c5cb5229b7969b2a5146855a337870f45aJim Miller        gLooperRoster.dump(fd, args);
54608fa40c5cb5229b7969b2a5146855a337870f45aJim Miller
54708fa40c5cb5229b7969b2a5146855a337870f45aJim Miller        bool dumpMem = false;
5489f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller        for (size_t i = 0; i < args.size(); i++) {
5499f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller            if (args[i] == String16("-m")) {
550ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller                dumpMem = true;
5519f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller            }
55208fa40c5cb5229b7969b2a5146855a337870f45aJim Miller        }
5539f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller        if (dumpMem) {
55408fa40c5cb5229b7969b2a5146855a337870f45aJim Miller            dumpMemoryAddresses(fd);
55508fa40c5cb5229b7969b2a5146855a337870f45aJim Miller        }
5569f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    }
5579f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    write(fd, result.string(), result.size());
55808fa40c5cb5229b7969b2a5146855a337870f45aJim Miller    return NO_ERROR;
5599f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller}
56008fa40c5cb5229b7969b2a5146855a337870f45aJim Miller
56108fa40c5cb5229b7969b2a5146855a337870f45aJim Millervoid MediaPlayerService::removeClient(wp<Client> client)
5629f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller{
563a7596147b43940cad3f76c53ed154ef088b9269bJim Miller    Mutex::Autolock lock(mLock);
5649f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    mClients.remove(client);
565a7596147b43940cad3f76c53ed154ef088b9269bJim Miller}
566a7596147b43940cad3f76c53ed154ef088b9269bJim Miller
5679f0753f5a378fc80da86305b33244acc6fc53f01Jim MillerMediaPlayerService::Client::Client(
5689f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller        const sp<MediaPlayerService>& service, pid_t pid,
5699f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller        int32_t connId, const sp<IMediaPlayerClient>& client,
5709f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller        int audioSessionId, uid_t uid)
5719f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller{
5729f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    ALOGV("Client(%d) constructor", connId);
5739f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    mPid = pid;
5749f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    mConnId = connId;
5759f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    mService = service;
576fe6439f02db3a541d77a7afb27e3bca1ae7493edJim Miller    mClient = client;
577fe6439f02db3a541d77a7afb27e3bca1ae7493edJim Miller    mLoop = false;
5789f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    mStatus = NO_INIT;
5799f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    mAudioSessionId = audioSessionId;
5809f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    mUID = uid;
5819f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    mRetransmitEndpointValid = false;
5829f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    mAudioAttributes = NULL;
5839f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller
5849f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller#if CALLBACK_ANTAGONIZER
5859f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    ALOGD("create Antagonizer");
58608fa40c5cb5229b7969b2a5146855a337870f45aJim Miller    mAntagonizer = new Antagonizer(notify, this);
5879f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller#endif
5889f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller}
5899f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller
5909f0753f5a378fc80da86305b33244acc6fc53f01Jim MillerMediaPlayerService::Client::~Client()
5919f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller{
5929f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    ALOGV("Client(%d) destructor pid = %d", mConnId, mPid);
5939f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    mAudioOutput.clear();
5949f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    wp<Client> client(this);
5959f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    disconnect();
5969f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    mService->removeClient(client);
5979f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    if (mAudioAttributes != NULL) {
5989f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller        free(mAudioAttributes);
599a7596147b43940cad3f76c53ed154ef088b9269bJim Miller    }
600a7596147b43940cad3f76c53ed154ef088b9269bJim Miller}
601a7596147b43940cad3f76c53ed154ef088b9269bJim Miller
6029f0753f5a378fc80da86305b33244acc6fc53f01Jim Millervoid MediaPlayerService::Client::disconnect()
6039f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller{
6049f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    ALOGV("disconnect(%d) from pid %d", mConnId, mPid);
6059f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    // grab local reference and clear main reference to prevent future
6069f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    // access to object
6079f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    sp<MediaPlayerBase> p;
6089f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    {
6099f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller        Mutex::Autolock l(mLock);
6109f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller        p = mPlayer;
6119f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller        mClient.clear();
6129f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    }
6139f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller
6149f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    mPlayer.clear();
6159f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller
6169f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    // clear the notification to prevent callbacks to dead client
6179f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    // and reset the player. We assume the player will serialize
6189f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    // access to itself if necessary.
619fe6439f02db3a541d77a7afb27e3bca1ae7493edJim Miller    if (p != 0) {
6209f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller        p->setNotifyCallback(0, 0);
621ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller#if CALLBACK_ANTAGONIZER
622ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        ALOGD("kill Antagonizer");
623ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        mAntagonizer->kill();
624ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller#endif
625ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        p->reset();
626ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    }
627ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller
6289f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    disconnectNativeWindow();
6299f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller
6309f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    IPCThreadState::self()->flushCommands();
6319f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller}
6329f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller
6339f0753f5a378fc80da86305b33244acc6fc53f01Jim Millersp<MediaPlayerBase> MediaPlayerService::Client::createPlayer(player_type playerType)
6349f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller{
6359f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    // determine if we have the right player type
6369f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    sp<MediaPlayerBase> p = mPlayer;
6379f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    if ((p != NULL) && (p->playerType() != playerType)) {
6389f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller        ALOGV("delete player");
6399f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller        p.clear();
6409f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    }
6419f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    if (p == NULL) {
642ba67aee02cf864793129976cd8a8a46e60c60577Jim Miller        p = MediaPlayerFactory::createPlayer(playerType, this, notify);
643ba67aee02cf864793129976cd8a8a46e60c60577Jim Miller    }
644ba67aee02cf864793129976cd8a8a46e60c60577Jim Miller
645ba67aee02cf864793129976cd8a8a46e60c60577Jim Miller    if (p != NULL) {
6469f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller        p->setUID(mUID);
6479f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    }
6489f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller
6499f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    return p;
6509f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller}
6519f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller
6529f0753f5a378fc80da86305b33244acc6fc53f01Jim Millersp<MediaPlayerBase> MediaPlayerService::Client::setDataSource_pre(
6539f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller        player_type playerType)
6549f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller{
6559f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    ALOGV("player type = %d", playerType);
6569f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller
6579f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    // create the right type of player
6589f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    sp<MediaPlayerBase> p = createPlayer(playerType);
6599f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    if (p == NULL) {
660ba67aee02cf864793129976cd8a8a46e60c60577Jim Miller        return p;
661ba67aee02cf864793129976cd8a8a46e60c60577Jim Miller    }
662ba67aee02cf864793129976cd8a8a46e60c60577Jim Miller
663ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    if (!p->hardwareOutput()) {
664ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        mAudioOutput = new AudioOutput(mAudioSessionId, IPCThreadState::self()->getCallingUid(),
665ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller                mPid, mAudioAttributes);
666ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
667ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    }
668ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller
669fe6439f02db3a541d77a7afb27e3bca1ae7493edJim Miller    return p;
670ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller}
671ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller
672ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Millervoid MediaPlayerService::Client::setDataSource_post(
673ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        const sp<MediaPlayerBase>& p,
674ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        status_t status)
675ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller{
676ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    ALOGV(" setDataSource");
677ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    mStatus = status;
678ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    if (mStatus != OK) {
679ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        ALOGE("  error: %d", mStatus);
680ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        return;
681ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    }
682ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller
683ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    // Set the re-transmission endpoint if one was chosen.
684ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    if (mRetransmitEndpointValid) {
685ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        mStatus = p->setRetransmitEndpoint(&mRetransmitEndpoint);
686ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        if (mStatus != NO_ERROR) {
687ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller            ALOGE("setRetransmitEndpoint error: %d", mStatus);
688ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        }
689ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    }
690ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller
691ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    if (mStatus == OK) {
692ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        mPlayer = p;
693ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    }
694ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller}
695ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller
696ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Millerstatus_t MediaPlayerService::Client::setDataSource(
697fe6439f02db3a541d77a7afb27e3bca1ae7493edJim Miller        const sp<IMediaHTTPService> &httpService,
698fe6439f02db3a541d77a7afb27e3bca1ae7493edJim Miller        const char *url,
699fe6439f02db3a541d77a7afb27e3bca1ae7493edJim Miller        const KeyedVector<String8, String8> *headers)
700fe6439f02db3a541d77a7afb27e3bca1ae7493edJim Miller{
701fe6439f02db3a541d77a7afb27e3bca1ae7493edJim Miller    ALOGV("setDataSource(%s)", url);
702ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    if (url == NULL)
703ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        return UNKNOWN_ERROR;
704ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller
705ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    if ((strncmp(url, "http://", 7) == 0) ||
706ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        (strncmp(url, "https://", 8) == 0) ||
707ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        (strncmp(url, "rtsp://", 7) == 0)) {
708ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        if (!checkPermission("android.permission.INTERNET")) {
709ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller            return PERMISSION_DENIED;
7109f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller        }
711ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    }
712ba67aee02cf864793129976cd8a8a46e60c60577Jim Miller
713ba67aee02cf864793129976cd8a8a46e60c60577Jim Miller    if (strncmp(url, "content://", 10) == 0) {
71499d6019bead4705b7e126e65b856d538417d4934Jim Miller        // get a filedescriptor for the content Uri and
715ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        // pass it to the setDataSource(fd) method
716ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller
717ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        String16 url16(url);
718ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        int fd = android::openContentProviderFile(url16);
719ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        if (fd < 0)
720ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        {
721ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller            ALOGE("Couldn't open fd for %s", url);
722ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller            return UNKNOWN_ERROR;
723ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        }
724ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        setDataSource(fd, 0, 0x7fffffffffLL); // this sets mStatus
725ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        close(fd);
726ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        return mStatus;
727ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    } else {
728ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        player_type playerType = MediaPlayerFactory::getPlayerType(this, url);
729ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        sp<MediaPlayerBase> p = setDataSource_pre(playerType);
730ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        if (p == NULL) {
731ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller            return NO_INIT;
732ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        }
733ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller
734ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        setDataSource_post(p, p->setDataSource(httpService, url, headers));
735ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller        return mStatus;
736ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    }
737ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller}
738ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller
739ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Millerstatus_t MediaPlayerService::Client::setDataSource(int fd, int64_t offset, int64_t length)
740ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller{
741ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    ALOGV("setDataSource fd=%d, offset=%lld, length=%lld", fd, offset, length);
7429f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    struct stat sb;
743ce7eb6daf06a88129da365eb2112537ce0bb1b75Jim Miller    int ret = fstat(fd, &sb);
74499d6019bead4705b7e126e65b856d538417d4934Jim Miller    if (ret != 0) {
74599d6019bead4705b7e126e65b856d538417d4934Jim Miller        ALOGE("fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
7469f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller        return UNKNOWN_ERROR;
7479f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    }
7489f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller
7499f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    ALOGV("st_dev  = %llu", sb.st_dev);
7509f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    ALOGV("st_mode = %u", sb.st_mode);
7519f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    ALOGV("st_uid  = %lu", static_cast<unsigned long>(sb.st_uid));
7529f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    ALOGV("st_gid  = %lu", static_cast<unsigned long>(sb.st_gid));
7539f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    ALOGV("st_size = %llu", sb.st_size);
7549f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller
7559f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    if (offset >= sb.st_size) {
7569f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller        ALOGE("offset error");
7579f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller        ::close(fd);
758fe6439f02db3a541d77a7afb27e3bca1ae7493edJim Miller        return UNKNOWN_ERROR;
759fe6439f02db3a541d77a7afb27e3bca1ae7493edJim Miller    }
7609f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    if (offset + length > sb.st_size) {
7619f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller        length = sb.st_size - offset;
7629f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller        ALOGV("calculated length = %lld", length);
7639f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    }
7649f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller
7659f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    player_type playerType = MediaPlayerFactory::getPlayerType(this,
7669f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller                                                               fd,
7679f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller                                                               offset,
7689f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller                                                               length);
7699f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    sp<MediaPlayerBase> p = setDataSource_pre(playerType);
7709f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller    if (p == NULL) {
7719f0753f5a378fc80da86305b33244acc6fc53f01Jim Miller        return NO_INIT;
77208fa40c5cb5229b7969b2a5146855a337870f45aJim Miller    }
773
774    // now set data source
775    setDataSource_post(p, p->setDataSource(fd, offset, length));
776    return mStatus;
777}
778
779status_t MediaPlayerService::Client::setDataSource(
780        const sp<IStreamSource> &source) {
781    // create the right type of player
782    player_type playerType = MediaPlayerFactory::getPlayerType(this, source);
783    sp<MediaPlayerBase> p = setDataSource_pre(playerType);
784    if (p == NULL) {
785        return NO_INIT;
786    }
787
788    // now set data source
789    setDataSource_post(p, p->setDataSource(source));
790    return mStatus;
791}
792
793status_t MediaPlayerService::Client::setDataSource(
794        const sp<IDataSource> &source) {
795    sp<DataSource> dataSource = DataSource::CreateFromIDataSource(source);
796    player_type playerType = MediaPlayerFactory::getPlayerType(this, dataSource);
797    sp<MediaPlayerBase> p = setDataSource_pre(playerType);
798    if (p == NULL) {
799        return NO_INIT;
800    }
801    // now set data source
802    setDataSource_post(p, p->setDataSource(dataSource));
803    return mStatus;
804}
805
806void MediaPlayerService::Client::disconnectNativeWindow() {
807    if (mConnectedWindow != NULL) {
808        status_t err = native_window_api_disconnect(mConnectedWindow.get(),
809                NATIVE_WINDOW_API_MEDIA);
810
811        if (err != OK) {
812            ALOGW("native_window_api_disconnect returned an error: %s (%d)",
813                    strerror(-err), err);
814        }
815    }
816    mConnectedWindow.clear();
817}
818
819status_t MediaPlayerService::Client::setVideoSurfaceTexture(
820        const sp<IGraphicBufferProducer>& bufferProducer)
821{
822    ALOGV("[%d] setVideoSurfaceTexture(%p)", mConnId, bufferProducer.get());
823    sp<MediaPlayerBase> p = getPlayer();
824    if (p == 0) return UNKNOWN_ERROR;
825
826    sp<IBinder> binder(IInterface::asBinder(bufferProducer));
827    if (mConnectedWindowBinder == binder) {
828        return OK;
829    }
830
831    sp<ANativeWindow> anw;
832    if (bufferProducer != NULL) {
833        anw = new Surface(bufferProducer, true /* controlledByApp */);
834        status_t err = native_window_api_connect(anw.get(),
835                NATIVE_WINDOW_API_MEDIA);
836
837        if (err != OK) {
838            ALOGE("setVideoSurfaceTexture failed: %d", err);
839            // Note that we must do the reset before disconnecting from the ANW.
840            // Otherwise queue/dequeue calls could be made on the disconnected
841            // ANW, which may result in errors.
842            reset();
843
844            disconnectNativeWindow();
845
846            return err;
847        }
848    }
849
850    // Note that we must set the player's new GraphicBufferProducer before
851    // disconnecting the old one.  Otherwise queue/dequeue calls could be made
852    // on the disconnected ANW, which may result in errors.
853    status_t err = p->setVideoSurfaceTexture(bufferProducer);
854
855    disconnectNativeWindow();
856
857    mConnectedWindow = anw;
858
859    if (err == OK) {
860        mConnectedWindowBinder = binder;
861    } else {
862        disconnectNativeWindow();
863    }
864
865    return err;
866}
867
868status_t MediaPlayerService::Client::invoke(const Parcel& request,
869                                            Parcel *reply)
870{
871    sp<MediaPlayerBase> p = getPlayer();
872    if (p == NULL) return UNKNOWN_ERROR;
873    return p->invoke(request, reply);
874}
875
876// This call doesn't need to access the native player.
877status_t MediaPlayerService::Client::setMetadataFilter(const Parcel& filter)
878{
879    status_t status;
880    media::Metadata::Filter allow, drop;
881
882    if (unmarshallFilter(filter, &allow, &status) &&
883        unmarshallFilter(filter, &drop, &status)) {
884        Mutex::Autolock lock(mLock);
885
886        mMetadataAllow = allow;
887        mMetadataDrop = drop;
888    }
889    return status;
890}
891
892status_t MediaPlayerService::Client::getMetadata(
893        bool update_only, bool /*apply_filter*/, Parcel *reply)
894{
895    sp<MediaPlayerBase> player = getPlayer();
896    if (player == 0) return UNKNOWN_ERROR;
897
898    status_t status;
899    // Placeholder for the return code, updated by the caller.
900    reply->writeInt32(-1);
901
902    media::Metadata::Filter ids;
903
904    // We don't block notifications while we fetch the data. We clear
905    // mMetadataUpdated first so we don't lose notifications happening
906    // during the rest of this call.
907    {
908        Mutex::Autolock lock(mLock);
909        if (update_only) {
910            ids = mMetadataUpdated;
911        }
912        mMetadataUpdated.clear();
913    }
914
915    media::Metadata metadata(reply);
916
917    metadata.appendHeader();
918    status = player->getMetadata(ids, reply);
919
920    if (status != OK) {
921        metadata.resetParcel();
922        ALOGE("getMetadata failed %d", status);
923        return status;
924    }
925
926    // FIXME: Implement filtering on the result. Not critical since
927    // filtering takes place on the update notifications already. This
928    // would be when all the metadata are fetch and a filter is set.
929
930    // Everything is fine, update the metadata length.
931    metadata.updateLength();
932    return OK;
933}
934
935status_t MediaPlayerService::Client::prepareAsync()
936{
937    ALOGV("[%d] prepareAsync", mConnId);
938    sp<MediaPlayerBase> p = getPlayer();
939    if (p == 0) return UNKNOWN_ERROR;
940    status_t ret = p->prepareAsync();
941#if CALLBACK_ANTAGONIZER
942    ALOGD("start Antagonizer");
943    if (ret == NO_ERROR) mAntagonizer->start();
944#endif
945    return ret;
946}
947
948status_t MediaPlayerService::Client::start()
949{
950    ALOGV("[%d] start", mConnId);
951    sp<MediaPlayerBase> p = getPlayer();
952    if (p == 0) return UNKNOWN_ERROR;
953    p->setLooping(mLoop);
954    return p->start();
955}
956
957status_t MediaPlayerService::Client::stop()
958{
959    ALOGV("[%d] stop", mConnId);
960    sp<MediaPlayerBase> p = getPlayer();
961    if (p == 0) return UNKNOWN_ERROR;
962    return p->stop();
963}
964
965status_t MediaPlayerService::Client::pause()
966{
967    ALOGV("[%d] pause", mConnId);
968    sp<MediaPlayerBase> p = getPlayer();
969    if (p == 0) return UNKNOWN_ERROR;
970    return p->pause();
971}
972
973status_t MediaPlayerService::Client::isPlaying(bool* state)
974{
975    *state = false;
976    sp<MediaPlayerBase> p = getPlayer();
977    if (p == 0) return UNKNOWN_ERROR;
978    *state = p->isPlaying();
979    ALOGV("[%d] isPlaying: %d", mConnId, *state);
980    return NO_ERROR;
981}
982
983status_t MediaPlayerService::Client::setPlaybackRate(float rate)
984{
985    ALOGV("[%d] setPlaybackRate(%f)", mConnId, rate);
986    sp<MediaPlayerBase> p = getPlayer();
987    if (p == 0) return UNKNOWN_ERROR;
988    return p->setPlaybackRate(rate);
989}
990
991status_t MediaPlayerService::Client::getCurrentPosition(int *msec)
992{
993    ALOGV("getCurrentPosition");
994    sp<MediaPlayerBase> p = getPlayer();
995    if (p == 0) return UNKNOWN_ERROR;
996    status_t ret = p->getCurrentPosition(msec);
997    if (ret == NO_ERROR) {
998        ALOGV("[%d] getCurrentPosition = %d", mConnId, *msec);
999    } else {
1000        ALOGE("getCurrentPosition returned %d", ret);
1001    }
1002    return ret;
1003}
1004
1005status_t MediaPlayerService::Client::getDuration(int *msec)
1006{
1007    ALOGV("getDuration");
1008    sp<MediaPlayerBase> p = getPlayer();
1009    if (p == 0) return UNKNOWN_ERROR;
1010    status_t ret = p->getDuration(msec);
1011    if (ret == NO_ERROR) {
1012        ALOGV("[%d] getDuration = %d", mConnId, *msec);
1013    } else {
1014        ALOGE("getDuration returned %d", ret);
1015    }
1016    return ret;
1017}
1018
1019status_t MediaPlayerService::Client::setNextPlayer(const sp<IMediaPlayer>& player) {
1020    ALOGV("setNextPlayer");
1021    Mutex::Autolock l(mLock);
1022    sp<Client> c = static_cast<Client*>(player.get());
1023    mNextClient = c;
1024
1025    if (c != NULL) {
1026        if (mAudioOutput != NULL) {
1027            mAudioOutput->setNextOutput(c->mAudioOutput);
1028        } else if ((mPlayer != NULL) && !mPlayer->hardwareOutput()) {
1029            ALOGE("no current audio output");
1030        }
1031
1032        if ((mPlayer != NULL) && (mNextClient->getPlayer() != NULL)) {
1033            mPlayer->setNextPlayer(mNextClient->getPlayer());
1034        }
1035    }
1036
1037    return OK;
1038}
1039
1040status_t MediaPlayerService::Client::seekTo(int msec)
1041{
1042    ALOGV("[%d] seekTo(%d)", mConnId, msec);
1043    sp<MediaPlayerBase> p = getPlayer();
1044    if (p == 0) return UNKNOWN_ERROR;
1045    return p->seekTo(msec);
1046}
1047
1048status_t MediaPlayerService::Client::reset()
1049{
1050    ALOGV("[%d] reset", mConnId);
1051    mRetransmitEndpointValid = false;
1052    sp<MediaPlayerBase> p = getPlayer();
1053    if (p == 0) return UNKNOWN_ERROR;
1054    return p->reset();
1055}
1056
1057status_t MediaPlayerService::Client::setAudioStreamType(audio_stream_type_t type)
1058{
1059    ALOGV("[%d] setAudioStreamType(%d)", mConnId, type);
1060    // TODO: for hardware output, call player instead
1061    Mutex::Autolock l(mLock);
1062    if (mAudioOutput != 0) mAudioOutput->setAudioStreamType(type);
1063    return NO_ERROR;
1064}
1065
1066status_t MediaPlayerService::Client::setAudioAttributes_l(const Parcel &parcel)
1067{
1068    if (mAudioAttributes != NULL) { free(mAudioAttributes); }
1069    mAudioAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t));
1070    unmarshallAudioAttributes(parcel, mAudioAttributes);
1071
1072    ALOGV("setAudioAttributes_l() usage=%d content=%d flags=0x%x tags=%s",
1073            mAudioAttributes->usage, mAudioAttributes->content_type, mAudioAttributes->flags,
1074            mAudioAttributes->tags);
1075
1076    if (mAudioOutput != 0) {
1077        mAudioOutput->setAudioAttributes(mAudioAttributes);
1078    }
1079    return NO_ERROR;
1080}
1081
1082status_t MediaPlayerService::Client::setLooping(int loop)
1083{
1084    ALOGV("[%d] setLooping(%d)", mConnId, loop);
1085    mLoop = loop;
1086    sp<MediaPlayerBase> p = getPlayer();
1087    if (p != 0) return p->setLooping(loop);
1088    return NO_ERROR;
1089}
1090
1091status_t MediaPlayerService::Client::setVolume(float leftVolume, float rightVolume)
1092{
1093    ALOGV("[%d] setVolume(%f, %f)", mConnId, leftVolume, rightVolume);
1094
1095    // for hardware output, call player instead
1096    sp<MediaPlayerBase> p = getPlayer();
1097    {
1098      Mutex::Autolock l(mLock);
1099      if (p != 0 && p->hardwareOutput()) {
1100          MediaPlayerHWInterface* hwp =
1101                  reinterpret_cast<MediaPlayerHWInterface*>(p.get());
1102          return hwp->setVolume(leftVolume, rightVolume);
1103      } else {
1104          if (mAudioOutput != 0) mAudioOutput->setVolume(leftVolume, rightVolume);
1105          return NO_ERROR;
1106      }
1107    }
1108
1109    return NO_ERROR;
1110}
1111
1112status_t MediaPlayerService::Client::setAuxEffectSendLevel(float level)
1113{
1114    ALOGV("[%d] setAuxEffectSendLevel(%f)", mConnId, level);
1115    Mutex::Autolock l(mLock);
1116    if (mAudioOutput != 0) return mAudioOutput->setAuxEffectSendLevel(level);
1117    return NO_ERROR;
1118}
1119
1120status_t MediaPlayerService::Client::attachAuxEffect(int effectId)
1121{
1122    ALOGV("[%d] attachAuxEffect(%d)", mConnId, effectId);
1123    Mutex::Autolock l(mLock);
1124    if (mAudioOutput != 0) return mAudioOutput->attachAuxEffect(effectId);
1125    return NO_ERROR;
1126}
1127
1128status_t MediaPlayerService::Client::setParameter(int key, const Parcel &request) {
1129    ALOGV("[%d] setParameter(%d)", mConnId, key);
1130    switch (key) {
1131    case KEY_PARAMETER_AUDIO_ATTRIBUTES:
1132    {
1133        Mutex::Autolock l(mLock);
1134        return setAudioAttributes_l(request);
1135    }
1136    default:
1137        sp<MediaPlayerBase> p = getPlayer();
1138        if (p == 0) { return UNKNOWN_ERROR; }
1139        return p->setParameter(key, request);
1140    }
1141}
1142
1143status_t MediaPlayerService::Client::getParameter(int key, Parcel *reply) {
1144    ALOGV("[%d] getParameter(%d)", mConnId, key);
1145    sp<MediaPlayerBase> p = getPlayer();
1146    if (p == 0) return UNKNOWN_ERROR;
1147    return p->getParameter(key, reply);
1148}
1149
1150status_t MediaPlayerService::Client::setRetransmitEndpoint(
1151        const struct sockaddr_in* endpoint) {
1152
1153    if (NULL != endpoint) {
1154        uint32_t a = ntohl(endpoint->sin_addr.s_addr);
1155        uint16_t p = ntohs(endpoint->sin_port);
1156        ALOGV("[%d] setRetransmitEndpoint(%u.%u.%u.%u:%hu)", mConnId,
1157                (a >> 24), (a >> 16) & 0xFF, (a >> 8) & 0xFF, (a & 0xFF), p);
1158    } else {
1159        ALOGV("[%d] setRetransmitEndpoint = <none>", mConnId);
1160    }
1161
1162    sp<MediaPlayerBase> p = getPlayer();
1163
1164    // Right now, the only valid time to set a retransmit endpoint is before
1165    // player selection has been made (since the presence or absence of a
1166    // retransmit endpoint is going to determine which player is selected during
1167    // setDataSource).
1168    if (p != 0) return INVALID_OPERATION;
1169
1170    if (NULL != endpoint) {
1171        mRetransmitEndpoint = *endpoint;
1172        mRetransmitEndpointValid = true;
1173    } else {
1174        mRetransmitEndpointValid = false;
1175    }
1176
1177    return NO_ERROR;
1178}
1179
1180status_t MediaPlayerService::Client::getRetransmitEndpoint(
1181        struct sockaddr_in* endpoint)
1182{
1183    if (NULL == endpoint)
1184        return BAD_VALUE;
1185
1186    sp<MediaPlayerBase> p = getPlayer();
1187
1188    if (p != NULL)
1189        return p->getRetransmitEndpoint(endpoint);
1190
1191    if (!mRetransmitEndpointValid)
1192        return NO_INIT;
1193
1194    *endpoint = mRetransmitEndpoint;
1195
1196    return NO_ERROR;
1197}
1198
1199void MediaPlayerService::Client::notify(
1200        void* cookie, int msg, int ext1, int ext2, const Parcel *obj)
1201{
1202    Client* client = static_cast<Client*>(cookie);
1203    if (client == NULL) {
1204        return;
1205    }
1206
1207    sp<IMediaPlayerClient> c;
1208    {
1209        Mutex::Autolock l(client->mLock);
1210        c = client->mClient;
1211        if (msg == MEDIA_PLAYBACK_COMPLETE && client->mNextClient != NULL) {
1212            if (client->mAudioOutput != NULL)
1213                client->mAudioOutput->switchToNextOutput();
1214            client->mNextClient->start();
1215            client->mNextClient->mClient->notify(MEDIA_INFO, MEDIA_INFO_STARTED_AS_NEXT, 0, obj);
1216        }
1217    }
1218
1219    if (MEDIA_INFO == msg &&
1220        MEDIA_INFO_METADATA_UPDATE == ext1) {
1221        const media::Metadata::Type metadata_type = ext2;
1222
1223        if(client->shouldDropMetadata(metadata_type)) {
1224            return;
1225        }
1226
1227        // Update the list of metadata that have changed. getMetadata
1228        // also access mMetadataUpdated and clears it.
1229        client->addNewMetadataUpdate(metadata_type);
1230    }
1231
1232    if (c != NULL) {
1233        ALOGV("[%d] notify (%p, %d, %d, %d)", client->mConnId, cookie, msg, ext1, ext2);
1234        c->notify(msg, ext1, ext2, obj);
1235    }
1236}
1237
1238
1239bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const
1240{
1241    Mutex::Autolock lock(mLock);
1242
1243    if (findMetadata(mMetadataDrop, code)) {
1244        return true;
1245    }
1246
1247    if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) {
1248        return false;
1249    } else {
1250        return true;
1251    }
1252}
1253
1254
1255void MediaPlayerService::Client::addNewMetadataUpdate(media::Metadata::Type metadata_type) {
1256    Mutex::Autolock lock(mLock);
1257    if (mMetadataUpdated.indexOf(metadata_type) < 0) {
1258        mMetadataUpdated.add(metadata_type);
1259    }
1260}
1261
1262#if CALLBACK_ANTAGONIZER
1263const int Antagonizer::interval = 10000; // 10 msecs
1264
1265Antagonizer::Antagonizer(notify_callback_f cb, void* client) :
1266    mExit(false), mActive(false), mClient(client), mCb(cb)
1267{
1268    createThread(callbackThread, this);
1269}
1270
1271void Antagonizer::kill()
1272{
1273    Mutex::Autolock _l(mLock);
1274    mActive = false;
1275    mExit = true;
1276    mCondition.wait(mLock);
1277}
1278
1279int Antagonizer::callbackThread(void* user)
1280{
1281    ALOGD("Antagonizer started");
1282    Antagonizer* p = reinterpret_cast<Antagonizer*>(user);
1283    while (!p->mExit) {
1284        if (p->mActive) {
1285            ALOGV("send event");
1286            p->mCb(p->mClient, 0, 0, 0);
1287        }
1288        usleep(interval);
1289    }
1290    Mutex::Autolock _l(p->mLock);
1291    p->mCondition.signal();
1292    ALOGD("Antagonizer stopped");
1293    return 0;
1294}
1295#endif
1296
1297#undef LOG_TAG
1298#define LOG_TAG "AudioSink"
1299MediaPlayerService::AudioOutput::AudioOutput(int sessionId, int uid, int pid,
1300        const audio_attributes_t* attr)
1301    : mCallback(NULL),
1302      mCallbackCookie(NULL),
1303      mCallbackData(NULL),
1304      mBytesWritten(0),
1305      mSessionId(sessionId),
1306      mUid(uid),
1307      mPid(pid),
1308      mFlags(AUDIO_OUTPUT_FLAG_NONE) {
1309    ALOGV("AudioOutput(%d)", sessionId);
1310    mStreamType = AUDIO_STREAM_MUSIC;
1311    mLeftVolume = 1.0;
1312    mRightVolume = 1.0;
1313    mPlaybackRatePermille = 1000;
1314    mSampleRateHz = 0;
1315    mMsecsPerFrame = 0;
1316    mAuxEffectId = 0;
1317    mSendLevel = 0.0;
1318    setMinBufferCount();
1319    mAttributes = attr;
1320}
1321
1322MediaPlayerService::AudioOutput::~AudioOutput()
1323{
1324    close();
1325    delete mCallbackData;
1326}
1327
1328void MediaPlayerService::AudioOutput::setMinBufferCount()
1329{
1330    char value[PROPERTY_VALUE_MAX];
1331    if (property_get("ro.kernel.qemu", value, 0)) {
1332        mIsOnEmulator = true;
1333        mMinBufferCount = 12;  // to prevent systematic buffer underrun for emulator
1334    }
1335}
1336
1337bool MediaPlayerService::AudioOutput::isOnEmulator()
1338{
1339    setMinBufferCount();
1340    return mIsOnEmulator;
1341}
1342
1343int MediaPlayerService::AudioOutput::getMinBufferCount()
1344{
1345    setMinBufferCount();
1346    return mMinBufferCount;
1347}
1348
1349ssize_t MediaPlayerService::AudioOutput::bufferSize() const
1350{
1351    if (mTrack == 0) return NO_INIT;
1352    return mTrack->frameCount() * frameSize();
1353}
1354
1355ssize_t MediaPlayerService::AudioOutput::frameCount() const
1356{
1357    if (mTrack == 0) return NO_INIT;
1358    return mTrack->frameCount();
1359}
1360
1361ssize_t MediaPlayerService::AudioOutput::channelCount() const
1362{
1363    if (mTrack == 0) return NO_INIT;
1364    return mTrack->channelCount();
1365}
1366
1367ssize_t MediaPlayerService::AudioOutput::frameSize() const
1368{
1369    if (mTrack == 0) return NO_INIT;
1370    return mTrack->frameSize();
1371}
1372
1373uint32_t MediaPlayerService::AudioOutput::latency () const
1374{
1375    if (mTrack == 0) return 0;
1376    return mTrack->latency();
1377}
1378
1379float MediaPlayerService::AudioOutput::msecsPerFrame() const
1380{
1381    return mMsecsPerFrame;
1382}
1383
1384status_t MediaPlayerService::AudioOutput::getPosition(uint32_t *position) const
1385{
1386    if (mTrack == 0) return NO_INIT;
1387    return mTrack->getPosition(position);
1388}
1389
1390status_t MediaPlayerService::AudioOutput::getTimestamp(AudioTimestamp &ts) const
1391{
1392    if (mTrack == 0) return NO_INIT;
1393    return mTrack->getTimestamp(ts);
1394}
1395
1396status_t MediaPlayerService::AudioOutput::getFramesWritten(uint32_t *frameswritten) const
1397{
1398    if (mTrack == 0) return NO_INIT;
1399    *frameswritten = mBytesWritten / frameSize();
1400    return OK;
1401}
1402
1403status_t MediaPlayerService::AudioOutput::setParameters(const String8& keyValuePairs)
1404{
1405    if (mTrack == 0) return NO_INIT;
1406    return mTrack->setParameters(keyValuePairs);
1407}
1408
1409String8  MediaPlayerService::AudioOutput::getParameters(const String8& keys)
1410{
1411    if (mTrack == 0) return String8::empty();
1412    return mTrack->getParameters(keys);
1413}
1414
1415void MediaPlayerService::AudioOutput::setAudioAttributes(const audio_attributes_t * attributes) {
1416    mAttributes = attributes;
1417}
1418
1419void MediaPlayerService::AudioOutput::deleteRecycledTrack()
1420{
1421    ALOGV("deleteRecycledTrack");
1422
1423    if (mRecycledTrack != 0) {
1424
1425        if (mCallbackData != NULL) {
1426            mCallbackData->setOutput(NULL);
1427            mCallbackData->endTrackSwitch();
1428        }
1429
1430        if ((mRecycledTrack->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) {
1431            mRecycledTrack->flush();
1432        }
1433        // An offloaded track isn't flushed because the STREAM_END is reported
1434        // slightly prematurely to allow time for the gapless track switch
1435        // but this means that if we decide not to recycle the track there
1436        // could be a small amount of residual data still playing. We leave
1437        // AudioFlinger to drain the track.
1438
1439        mRecycledTrack.clear();
1440        delete mCallbackData;
1441        mCallbackData = NULL;
1442        close();
1443    }
1444}
1445
1446status_t MediaPlayerService::AudioOutput::open(
1447        uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
1448        audio_format_t format, int bufferCount,
1449        AudioCallback cb, void *cookie,
1450        audio_output_flags_t flags,
1451        const audio_offload_info_t *offloadInfo)
1452{
1453    mCallback = cb;
1454    mCallbackCookie = cookie;
1455
1456    // Check argument "bufferCount" against the mininum buffer count
1457    if (bufferCount < mMinBufferCount) {
1458        ALOGD("bufferCount (%d) is too small and increased to %d", bufferCount, mMinBufferCount);
1459        bufferCount = mMinBufferCount;
1460
1461    }
1462    ALOGV("open(%u, %d, 0x%x, 0x%x, %d, %d 0x%x)", sampleRate, channelCount, channelMask,
1463                format, bufferCount, mSessionId, flags);
1464    uint32_t afSampleRate;
1465    size_t afFrameCount;
1466    size_t frameCount;
1467
1468    // offloading is only supported in callback mode for now.
1469    // offloadInfo must be present if offload flag is set
1470    if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) &&
1471            ((cb == NULL) || (offloadInfo == NULL))) {
1472        return BAD_VALUE;
1473    }
1474
1475    if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1476        frameCount = 0; // AudioTrack will get frame count from AudioFlinger
1477    } else {
1478        uint32_t afSampleRate;
1479        size_t afFrameCount;
1480
1481        if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) {
1482            return NO_INIT;
1483        }
1484        if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) {
1485            return NO_INIT;
1486        }
1487
1488        frameCount = (sampleRate*afFrameCount*bufferCount)/afSampleRate;
1489    }
1490
1491    if (channelMask == CHANNEL_MASK_USE_CHANNEL_ORDER) {
1492        channelMask = audio_channel_out_mask_from_count(channelCount);
1493        if (0 == channelMask) {
1494            ALOGE("open() error, can\'t derive mask for %d audio channels", channelCount);
1495            return NO_INIT;
1496        }
1497    }
1498
1499    // Check whether we can recycle the track
1500    bool reuse = false;
1501    bool bothOffloaded = false;
1502
1503    if (mRecycledTrack != 0) {
1504        // check whether we are switching between two offloaded tracks
1505        bothOffloaded = (flags & mRecycledTrack->getFlags()
1506                                & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0;
1507
1508        // check if the existing track can be reused as-is, or if a new track needs to be created.
1509        reuse = true;
1510
1511        if ((mCallbackData == NULL && mCallback != NULL) ||
1512                (mCallbackData != NULL && mCallback == NULL)) {
1513            // recycled track uses callbacks but the caller wants to use writes, or vice versa
1514            ALOGV("can't chain callback and write");
1515            reuse = false;
1516        } else if ((mRecycledTrack->getSampleRate() != sampleRate) ||
1517                (mRecycledTrack->channelCount() != (uint32_t)channelCount) ) {
1518            ALOGV("samplerate, channelcount differ: %u/%u Hz, %u/%d ch",
1519                  mRecycledTrack->getSampleRate(), sampleRate,
1520                  mRecycledTrack->channelCount(), channelCount);
1521            reuse = false;
1522        } else if (flags != mFlags) {
1523            ALOGV("output flags differ %08x/%08x", flags, mFlags);
1524            reuse = false;
1525        } else if (mRecycledTrack->format() != format) {
1526            reuse = false;
1527        }
1528    } else {
1529        ALOGV("no track available to recycle");
1530    }
1531
1532    ALOGV_IF(bothOffloaded, "both tracks offloaded");
1533
1534    // If we can't recycle and both tracks are offloaded
1535    // we must close the previous output before opening a new one
1536    if (bothOffloaded && !reuse) {
1537        ALOGV("both offloaded and not recycling");
1538        deleteRecycledTrack();
1539    }
1540
1541    sp<AudioTrack> t;
1542    CallbackData *newcbd = NULL;
1543
1544    // We don't attempt to create a new track if we are recycling an
1545    // offloaded track. But, if we are recycling a non-offloaded or we
1546    // are switching where one is offloaded and one isn't then we create
1547    // the new track in advance so that we can read additional stream info
1548
1549    if (!(reuse && bothOffloaded)) {
1550        ALOGV("creating new AudioTrack");
1551
1552        if (mCallback != NULL) {
1553            newcbd = new CallbackData(this);
1554            t = new AudioTrack(
1555                    mStreamType,
1556                    sampleRate,
1557                    format,
1558                    channelMask,
1559                    frameCount,
1560                    flags,
1561                    CallbackWrapper,
1562                    newcbd,
1563                    0,  // notification frames
1564                    mSessionId,
1565                    AudioTrack::TRANSFER_CALLBACK,
1566                    offloadInfo,
1567                    mUid,
1568                    mPid,
1569                    mAttributes);
1570        } else {
1571            t = new AudioTrack(
1572                    mStreamType,
1573                    sampleRate,
1574                    format,
1575                    channelMask,
1576                    frameCount,
1577                    flags,
1578                    NULL, // callback
1579                    NULL, // user data
1580                    0, // notification frames
1581                    mSessionId,
1582                    AudioTrack::TRANSFER_DEFAULT,
1583                    NULL, // offload info
1584                    mUid,
1585                    mPid,
1586                    mAttributes);
1587        }
1588
1589        if ((t == 0) || (t->initCheck() != NO_ERROR)) {
1590            ALOGE("Unable to create audio track");
1591            delete newcbd;
1592            return NO_INIT;
1593        } else {
1594            // successful AudioTrack initialization implies a legacy stream type was generated
1595            // from the audio attributes
1596            mStreamType = t->streamType();
1597        }
1598    }
1599
1600    if (reuse) {
1601        CHECK(mRecycledTrack != NULL);
1602
1603        if (!bothOffloaded) {
1604            if (mRecycledTrack->frameCount() != t->frameCount()) {
1605                ALOGV("framecount differs: %u/%u frames",
1606                      mRecycledTrack->frameCount(), t->frameCount());
1607                reuse = false;
1608            }
1609        }
1610
1611        if (reuse) {
1612            ALOGV("chaining to next output and recycling track");
1613            close();
1614            mTrack = mRecycledTrack;
1615            mRecycledTrack.clear();
1616            if (mCallbackData != NULL) {
1617                mCallbackData->setOutput(this);
1618            }
1619            delete newcbd;
1620            return OK;
1621        }
1622    }
1623
1624    // we're not going to reuse the track, unblock and flush it
1625    // this was done earlier if both tracks are offloaded
1626    if (!bothOffloaded) {
1627        deleteRecycledTrack();
1628    }
1629
1630    CHECK((t != NULL) && ((mCallback == NULL) || (newcbd != NULL)));
1631
1632    mCallbackData = newcbd;
1633    ALOGV("setVolume");
1634    t->setVolume(mLeftVolume, mRightVolume);
1635
1636    mSampleRateHz = sampleRate;
1637    mFlags = flags;
1638    mMsecsPerFrame = mPlaybackRatePermille / (float) sampleRate;
1639    uint32_t pos;
1640    if (t->getPosition(&pos) == OK) {
1641        mBytesWritten = uint64_t(pos) * t->frameSize();
1642    }
1643    mTrack = t;
1644
1645    status_t res = NO_ERROR;
1646    if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) {
1647        res = t->setSampleRate(mPlaybackRatePermille * mSampleRateHz / 1000);
1648        if (res == NO_ERROR) {
1649            t->setAuxEffectSendLevel(mSendLevel);
1650            res = t->attachAuxEffect(mAuxEffectId);
1651        }
1652    }
1653    ALOGV("open() DONE status %d", res);
1654    return res;
1655}
1656
1657status_t MediaPlayerService::AudioOutput::start()
1658{
1659    ALOGV("start");
1660    if (mCallbackData != NULL) {
1661        mCallbackData->endTrackSwitch();
1662    }
1663    if (mTrack != 0) {
1664        mTrack->setVolume(mLeftVolume, mRightVolume);
1665        mTrack->setAuxEffectSendLevel(mSendLevel);
1666        return mTrack->start();
1667    }
1668    return NO_INIT;
1669}
1670
1671void MediaPlayerService::AudioOutput::setNextOutput(const sp<AudioOutput>& nextOutput) {
1672    mNextOutput = nextOutput;
1673}
1674
1675
1676void MediaPlayerService::AudioOutput::switchToNextOutput() {
1677    ALOGV("switchToNextOutput");
1678    if (mNextOutput != NULL) {
1679        if (mCallbackData != NULL) {
1680            mCallbackData->beginTrackSwitch();
1681        }
1682        delete mNextOutput->mCallbackData;
1683        mNextOutput->mCallbackData = mCallbackData;
1684        mCallbackData = NULL;
1685        mNextOutput->mRecycledTrack = mTrack;
1686        mTrack.clear();
1687        mNextOutput->mSampleRateHz = mSampleRateHz;
1688        mNextOutput->mMsecsPerFrame = mMsecsPerFrame;
1689        mNextOutput->mBytesWritten = mBytesWritten;
1690        mNextOutput->mFlags = mFlags;
1691    }
1692}
1693
1694ssize_t MediaPlayerService::AudioOutput::write(const void* buffer, size_t size, bool blocking)
1695{
1696    LOG_ALWAYS_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback.");
1697
1698    //ALOGV("write(%p, %u)", buffer, size);
1699    if (mTrack != 0) {
1700        ssize_t ret = mTrack->write(buffer, size, blocking);
1701        if (ret >= 0) {
1702            mBytesWritten += ret;
1703        }
1704        return ret;
1705    }
1706    return NO_INIT;
1707}
1708
1709void MediaPlayerService::AudioOutput::stop()
1710{
1711    ALOGV("stop");
1712    if (mTrack != 0) mTrack->stop();
1713}
1714
1715void MediaPlayerService::AudioOutput::flush()
1716{
1717    ALOGV("flush");
1718    if (mTrack != 0) mTrack->flush();
1719}
1720
1721void MediaPlayerService::AudioOutput::pause()
1722{
1723    ALOGV("pause");
1724    if (mTrack != 0) mTrack->pause();
1725}
1726
1727void MediaPlayerService::AudioOutput::close()
1728{
1729    ALOGV("close");
1730    mTrack.clear();
1731}
1732
1733void MediaPlayerService::AudioOutput::setVolume(float left, float right)
1734{
1735    ALOGV("setVolume(%f, %f)", left, right);
1736    mLeftVolume = left;
1737    mRightVolume = right;
1738    if (mTrack != 0) {
1739        mTrack->setVolume(left, right);
1740    }
1741}
1742
1743status_t MediaPlayerService::AudioOutput::setPlaybackRatePermille(int32_t ratePermille)
1744{
1745    ALOGV("setPlaybackRatePermille(%d)", ratePermille);
1746    status_t res = NO_ERROR;
1747    if (mTrack != 0) {
1748        res = mTrack->setSampleRate(ratePermille * mSampleRateHz / 1000);
1749    } else {
1750        res = NO_INIT;
1751    }
1752    mPlaybackRatePermille = ratePermille;
1753    if (mSampleRateHz != 0) {
1754        mMsecsPerFrame = mPlaybackRatePermille / (float) mSampleRateHz;
1755    }
1756    return res;
1757}
1758
1759status_t MediaPlayerService::AudioOutput::setAuxEffectSendLevel(float level)
1760{
1761    ALOGV("setAuxEffectSendLevel(%f)", level);
1762    mSendLevel = level;
1763    if (mTrack != 0) {
1764        return mTrack->setAuxEffectSendLevel(level);
1765    }
1766    return NO_ERROR;
1767}
1768
1769status_t MediaPlayerService::AudioOutput::attachAuxEffect(int effectId)
1770{
1771    ALOGV("attachAuxEffect(%d)", effectId);
1772    mAuxEffectId = effectId;
1773    if (mTrack != 0) {
1774        return mTrack->attachAuxEffect(effectId);
1775    }
1776    return NO_ERROR;
1777}
1778
1779// static
1780void MediaPlayerService::AudioOutput::CallbackWrapper(
1781        int event, void *cookie, void *info) {
1782    //ALOGV("callbackwrapper");
1783    CallbackData *data = (CallbackData*)cookie;
1784    data->lock();
1785    AudioOutput *me = data->getOutput();
1786    AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info;
1787    if (me == NULL) {
1788        // no output set, likely because the track was scheduled to be reused
1789        // by another player, but the format turned out to be incompatible.
1790        data->unlock();
1791        if (buffer != NULL) {
1792            buffer->size = 0;
1793        }
1794        return;
1795    }
1796
1797    switch(event) {
1798    case AudioTrack::EVENT_MORE_DATA: {
1799        size_t actualSize = (*me->mCallback)(
1800                me, buffer->raw, buffer->size, me->mCallbackCookie,
1801                CB_EVENT_FILL_BUFFER);
1802
1803        if ((me->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0 &&
1804            actualSize == 0 && buffer->size > 0 && me->mNextOutput == NULL) {
1805            // We've reached EOS but the audio track is not stopped yet,
1806            // keep playing silence.
1807
1808            memset(buffer->raw, 0, buffer->size);
1809            actualSize = buffer->size;
1810        }
1811
1812        buffer->size = actualSize;
1813        } break;
1814
1815
1816    case AudioTrack::EVENT_STREAM_END:
1817        ALOGV("callbackwrapper: deliver EVENT_STREAM_END");
1818        (*me->mCallback)(me, NULL /* buffer */, 0 /* size */,
1819                me->mCallbackCookie, CB_EVENT_STREAM_END);
1820        break;
1821
1822    case AudioTrack::EVENT_NEW_IAUDIOTRACK :
1823        ALOGV("callbackwrapper: deliver EVENT_TEAR_DOWN");
1824        (*me->mCallback)(me,  NULL /* buffer */, 0 /* size */,
1825                me->mCallbackCookie, CB_EVENT_TEAR_DOWN);
1826        break;
1827
1828    default:
1829        ALOGE("received unknown event type: %d inside CallbackWrapper !", event);
1830    }
1831
1832    data->unlock();
1833}
1834
1835int MediaPlayerService::AudioOutput::getSessionId() const
1836{
1837    return mSessionId;
1838}
1839
1840uint32_t MediaPlayerService::AudioOutput::getSampleRate() const
1841{
1842    if (mTrack == 0) return 0;
1843    return mTrack->getSampleRate();
1844}
1845
1846////////////////////////////////////////////////////////////////////////////////
1847
1848struct CallbackThread : public Thread {
1849    CallbackThread(const wp<MediaPlayerBase::AudioSink> &sink,
1850                   MediaPlayerBase::AudioSink::AudioCallback cb,
1851                   void *cookie);
1852
1853protected:
1854    virtual ~CallbackThread();
1855
1856    virtual bool threadLoop();
1857
1858private:
1859    wp<MediaPlayerBase::AudioSink> mSink;
1860    MediaPlayerBase::AudioSink::AudioCallback mCallback;
1861    void *mCookie;
1862    void *mBuffer;
1863    size_t mBufferSize;
1864
1865    CallbackThread(const CallbackThread &);
1866    CallbackThread &operator=(const CallbackThread &);
1867};
1868
1869CallbackThread::CallbackThread(
1870        const wp<MediaPlayerBase::AudioSink> &sink,
1871        MediaPlayerBase::AudioSink::AudioCallback cb,
1872        void *cookie)
1873    : mSink(sink),
1874      mCallback(cb),
1875      mCookie(cookie),
1876      mBuffer(NULL),
1877      mBufferSize(0) {
1878}
1879
1880CallbackThread::~CallbackThread() {
1881    if (mBuffer) {
1882        free(mBuffer);
1883        mBuffer = NULL;
1884    }
1885}
1886
1887bool CallbackThread::threadLoop() {
1888    sp<MediaPlayerBase::AudioSink> sink = mSink.promote();
1889    if (sink == NULL) {
1890        return false;
1891    }
1892
1893    if (mBuffer == NULL) {
1894        mBufferSize = sink->bufferSize();
1895        mBuffer = malloc(mBufferSize);
1896    }
1897
1898    size_t actualSize =
1899        (*mCallback)(sink.get(), mBuffer, mBufferSize, mCookie,
1900                MediaPlayerBase::AudioSink::CB_EVENT_FILL_BUFFER);
1901
1902    if (actualSize > 0) {
1903        sink->write(mBuffer, actualSize);
1904        // Could return false on sink->write() error or short count.
1905        // Not necessarily appropriate but would work for AudioCache behavior.
1906    }
1907
1908    return true;
1909}
1910
1911////////////////////////////////////////////////////////////////////////////////
1912
1913void MediaPlayerService::addBatteryData(uint32_t params)
1914{
1915    Mutex::Autolock lock(mLock);
1916
1917    int32_t time = systemTime() / 1000000L;
1918
1919    // change audio output devices. This notification comes from AudioFlinger
1920    if ((params & kBatteryDataSpeakerOn)
1921            || (params & kBatteryDataOtherAudioDeviceOn)) {
1922
1923        int deviceOn[NUM_AUDIO_DEVICES];
1924        for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1925            deviceOn[i] = 0;
1926        }
1927
1928        if ((params & kBatteryDataSpeakerOn)
1929                && (params & kBatteryDataOtherAudioDeviceOn)) {
1930            deviceOn[SPEAKER_AND_OTHER] = 1;
1931        } else if (params & kBatteryDataSpeakerOn) {
1932            deviceOn[SPEAKER] = 1;
1933        } else {
1934            deviceOn[OTHER_AUDIO_DEVICE] = 1;
1935        }
1936
1937        for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1938            if (mBatteryAudio.deviceOn[i] != deviceOn[i]){
1939
1940                if (mBatteryAudio.refCount > 0) { // if playing audio
1941                    if (!deviceOn[i]) {
1942                        mBatteryAudio.lastTime[i] += time;
1943                        mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
1944                        mBatteryAudio.lastTime[i] = 0;
1945                    } else {
1946                        mBatteryAudio.lastTime[i] = 0 - time;
1947                    }
1948                }
1949
1950                mBatteryAudio.deviceOn[i] = deviceOn[i];
1951            }
1952        }
1953        return;
1954    }
1955
1956    // an audio stream is started
1957    if (params & kBatteryDataAudioFlingerStart) {
1958        // record the start time only if currently no other audio
1959        // is being played
1960        if (mBatteryAudio.refCount == 0) {
1961            for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1962                if (mBatteryAudio.deviceOn[i]) {
1963                    mBatteryAudio.lastTime[i] -= time;
1964                }
1965            }
1966        }
1967
1968        mBatteryAudio.refCount ++;
1969        return;
1970
1971    } else if (params & kBatteryDataAudioFlingerStop) {
1972        if (mBatteryAudio.refCount <= 0) {
1973            ALOGW("Battery track warning: refCount is <= 0");
1974            return;
1975        }
1976
1977        // record the stop time only if currently this is the only
1978        // audio being played
1979        if (mBatteryAudio.refCount == 1) {
1980            for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
1981                if (mBatteryAudio.deviceOn[i]) {
1982                    mBatteryAudio.lastTime[i] += time;
1983                    mBatteryAudio.totalTime[i] += mBatteryAudio.lastTime[i];
1984                    mBatteryAudio.lastTime[i] = 0;
1985                }
1986            }
1987        }
1988
1989        mBatteryAudio.refCount --;
1990        return;
1991    }
1992
1993    int uid = IPCThreadState::self()->getCallingUid();
1994    if (uid == AID_MEDIA) {
1995        return;
1996    }
1997    int index = mBatteryData.indexOfKey(uid);
1998
1999    if (index < 0) { // create a new entry for this UID
2000        BatteryUsageInfo info;
2001        info.audioTotalTime = 0;
2002        info.videoTotalTime = 0;
2003        info.audioLastTime = 0;
2004        info.videoLastTime = 0;
2005        info.refCount = 0;
2006
2007        if (mBatteryData.add(uid, info) == NO_MEMORY) {
2008            ALOGE("Battery track error: no memory for new app");
2009            return;
2010        }
2011    }
2012
2013    BatteryUsageInfo &info = mBatteryData.editValueFor(uid);
2014
2015    if (params & kBatteryDataCodecStarted) {
2016        if (params & kBatteryDataTrackAudio) {
2017            info.audioLastTime -= time;
2018            info.refCount ++;
2019        }
2020        if (params & kBatteryDataTrackVideo) {
2021            info.videoLastTime -= time;
2022            info.refCount ++;
2023        }
2024    } else {
2025        if (info.refCount == 0) {
2026            ALOGW("Battery track warning: refCount is already 0");
2027            return;
2028        } else if (info.refCount < 0) {
2029            ALOGE("Battery track error: refCount < 0");
2030            mBatteryData.removeItem(uid);
2031            return;
2032        }
2033
2034        if (params & kBatteryDataTrackAudio) {
2035            info.audioLastTime += time;
2036            info.refCount --;
2037        }
2038        if (params & kBatteryDataTrackVideo) {
2039            info.videoLastTime += time;
2040            info.refCount --;
2041        }
2042
2043        // no stream is being played by this UID
2044        if (info.refCount == 0) {
2045            info.audioTotalTime += info.audioLastTime;
2046            info.audioLastTime = 0;
2047            info.videoTotalTime += info.videoLastTime;
2048            info.videoLastTime = 0;
2049        }
2050    }
2051}
2052
2053status_t MediaPlayerService::pullBatteryData(Parcel* reply) {
2054    Mutex::Autolock lock(mLock);
2055
2056    // audio output devices usage
2057    int32_t time = systemTime() / 1000000L; //in ms
2058    int32_t totalTime;
2059
2060    for (int i = 0; i < NUM_AUDIO_DEVICES; i++) {
2061        totalTime = mBatteryAudio.totalTime[i];
2062
2063        if (mBatteryAudio.deviceOn[i]
2064            && (mBatteryAudio.lastTime[i] != 0)) {
2065                int32_t tmpTime = mBatteryAudio.lastTime[i] + time;
2066                totalTime += tmpTime;
2067        }
2068
2069        reply->writeInt32(totalTime);
2070        // reset the total time
2071        mBatteryAudio.totalTime[i] = 0;
2072   }
2073
2074    // codec usage
2075    BatteryUsageInfo info;
2076    int size = mBatteryData.size();
2077
2078    reply->writeInt32(size);
2079    int i = 0;
2080
2081    while (i < size) {
2082        info = mBatteryData.valueAt(i);
2083
2084        reply->writeInt32(mBatteryData.keyAt(i)); //UID
2085        reply->writeInt32(info.audioTotalTime);
2086        reply->writeInt32(info.videoTotalTime);
2087
2088        info.audioTotalTime = 0;
2089        info.videoTotalTime = 0;
2090
2091        // remove the UID entry where no stream is being played
2092        if (info.refCount <= 0) {
2093            mBatteryData.removeItemsAt(i);
2094            size --;
2095            i --;
2096        }
2097        i++;
2098    }
2099    return NO_ERROR;
2100}
2101} // namespace android
2102