1 /*
2  * Copyright (C) 2007 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef ANDROID_MEDIAPLAYERINTERFACE_H
18 #define ANDROID_MEDIAPLAYERINTERFACE_H
19 
20 #ifdef __cplusplus
21 
22 #include <sys/types.h>
23 #include <utils/Errors.h>
24 #include <utils/KeyedVector.h>
25 #include <utils/String8.h>
26 #include <utils/RefBase.h>
27 
28 #include <media/mediaplayer.h>
29 #include <media/AudioResamplerPublic.h>
30 #include <media/AudioSystem.h>
31 #include <media/AudioTimestamp.h>
32 #include <media/AVSyncSettings.h>
33 #include <media/Metadata.h>
34 
35 // Fwd decl to make sure everyone agrees that the scope of struct sockaddr_in is
36 // global, and not in android::
37 struct sockaddr_in;
38 
39 namespace android {
40 
41 class DataSource;
42 class Parcel;
43 class Surface;
44 class IGraphicBufferProducer;
45 
46 template<typename T> class SortedVector;
47 
48 enum player_type {
49     STAGEFRIGHT_PLAYER = 3,
50     NU_PLAYER = 4,
51     // Test players are available only in the 'test' and 'eng' builds.
52     // The shared library with the test player is passed passed as an
53     // argument to the 'test:' url in the setDataSource call.
54     TEST_PLAYER = 5,
55 };
56 
57 
58 #define DEFAULT_AUDIOSINK_BUFFERCOUNT 4
59 #define DEFAULT_AUDIOSINK_BUFFERSIZE 1200
60 #define DEFAULT_AUDIOSINK_SAMPLERATE 44100
61 
62 // when the channel mask isn't known, use the channel count to derive a mask in AudioSink::open()
63 #define CHANNEL_MASK_USE_CHANNEL_ORDER 0
64 
65 // duration below which we do not allow deep audio buffering
66 #define AUDIO_SINK_MIN_DEEP_BUFFER_DURATION_US 5000000
67 
68 // callback mechanism for passing messages to MediaPlayer object
69 typedef void (*notify_callback_f)(void* cookie,
70         int msg, int ext1, int ext2, const Parcel *obj);
71 
72 // abstract base class - use MediaPlayerInterface
73 class MediaPlayerBase : public RefBase
74 {
75 public:
76     // AudioSink: abstraction layer for audio output
77     class AudioSink : public RefBase {
78     public:
79         enum cb_event_t {
80             CB_EVENT_FILL_BUFFER,   // Request to write more data to buffer.
81             CB_EVENT_STREAM_END,    // Sent after all the buffers queued in AF and HW are played
82                                     // back (after stop is called)
83             CB_EVENT_TEAR_DOWN      // The AudioTrack was invalidated due to use case change:
84                                     // Need to re-evaluate offloading options
85         };
86 
87         // Callback returns the number of bytes actually written to the buffer.
88         typedef size_t (*AudioCallback)(
89                 AudioSink *audioSink, void *buffer, size_t size, void *cookie,
90                         cb_event_t event);
91 
~AudioSink()92         virtual             ~AudioSink() {}
93         virtual bool        ready() const = 0; // audio output is open and ready
94         virtual ssize_t     bufferSize() const = 0;
95         virtual ssize_t     frameCount() const = 0;
96         virtual ssize_t     channelCount() const = 0;
97         virtual ssize_t     frameSize() const = 0;
98         virtual uint32_t    latency() const = 0;
99         virtual float       msecsPerFrame() const = 0;
100         virtual status_t    getPosition(uint32_t *position) const = 0;
101         virtual status_t    getTimestamp(AudioTimestamp &ts) const = 0;
102         virtual status_t    getFramesWritten(uint32_t *frameswritten) const = 0;
103         virtual int         getSessionId() const = 0;
104         virtual audio_stream_type_t getAudioStreamType() const = 0;
105         virtual uint32_t    getSampleRate() const = 0;
106 
107         // If no callback is specified, use the "write" API below to submit
108         // audio data.
109         virtual status_t    open(
110                 uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
111                 audio_format_t format=AUDIO_FORMAT_PCM_16_BIT,
112                 int bufferCount=DEFAULT_AUDIOSINK_BUFFERCOUNT,
113                 AudioCallback cb = NULL,
114                 void *cookie = NULL,
115                 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE,
116                 const audio_offload_info_t *offloadInfo = NULL,
117                 bool doNotReconnect = false,
118                 uint32_t suggestedFrameCount = 0) = 0;
119 
120         virtual status_t    start() = 0;
121 
122         /* Input parameter |size| is in byte units stored in |buffer|.
123          * Data is copied over and actual number of bytes written (>= 0)
124          * is returned, or no data is copied and a negative status code
125          * is returned (even when |blocking| is true).
126          * When |blocking| is false, AudioSink will immediately return after
127          * part of or full |buffer| is copied over.
128          * When |blocking| is true, AudioSink will wait to copy the entire
129          * buffer, unless an error occurs or the copy operation is
130          * prematurely stopped.
131          */
132         virtual ssize_t     write(const void* buffer, size_t size, bool blocking = true) = 0;
133 
134         virtual void        stop() = 0;
135         virtual void        flush() = 0;
136         virtual void        pause() = 0;
137         virtual void        close() = 0;
138 
139         virtual status_t    setPlaybackRate(const AudioPlaybackRate& rate) = 0;
140         virtual status_t    getPlaybackRate(AudioPlaybackRate* rate /* nonnull */) = 0;
needsTrailingPadding()141         virtual bool        needsTrailingPadding() { return true; }
142 
setParameters(const String8 &)143         virtual status_t    setParameters(const String8& /* keyValuePairs */) { return NO_ERROR; }
getParameters(const String8 &)144         virtual String8     getParameters(const String8& /* keys */) { return String8::empty(); }
145     };
146 
MediaPlayerBase()147                         MediaPlayerBase() : mCookie(0), mNotify(0) {}
~MediaPlayerBase()148     virtual             ~MediaPlayerBase() {}
149     virtual status_t    initCheck() = 0;
150     virtual bool        hardwareOutput() = 0;
151 
setUID(uid_t)152     virtual status_t    setUID(uid_t /* uid */) {
153         return INVALID_OPERATION;
154     }
155 
156     virtual status_t    setDataSource(
157             const sp<IMediaHTTPService> &httpService,
158             const char *url,
159             const KeyedVector<String8, String8> *headers = NULL) = 0;
160 
161     virtual status_t    setDataSource(int fd, int64_t offset, int64_t length) = 0;
162 
setDataSource(const sp<IStreamSource> &)163     virtual status_t    setDataSource(const sp<IStreamSource>& /* source */) {
164         return INVALID_OPERATION;
165     }
166 
setDataSource(const sp<DataSource> &)167     virtual status_t    setDataSource(const sp<DataSource>& /* source */) {
168         return INVALID_OPERATION;
169     }
170 
171     // pass the buffered IGraphicBufferProducer to the media player service
172     virtual status_t    setVideoSurfaceTexture(
173                                 const sp<IGraphicBufferProducer>& bufferProducer) = 0;
174 
175     virtual status_t    prepare() = 0;
176     virtual status_t    prepareAsync() = 0;
177     virtual status_t    start() = 0;
178     virtual status_t    stop() = 0;
179     virtual status_t    pause() = 0;
180     virtual bool        isPlaying() = 0;
setPlaybackSettings(const AudioPlaybackRate & rate)181     virtual status_t    setPlaybackSettings(const AudioPlaybackRate& rate) {
182         // by default, players only support setting rate to the default
183         if (!isAudioPlaybackRateEqual(rate, AUDIO_PLAYBACK_RATE_DEFAULT)) {
184             return BAD_VALUE;
185         }
186         return OK;
187     }
getPlaybackSettings(AudioPlaybackRate * rate)188     virtual status_t    getPlaybackSettings(AudioPlaybackRate* rate /* nonnull */) {
189         *rate = AUDIO_PLAYBACK_RATE_DEFAULT;
190         return OK;
191     }
setSyncSettings(const AVSyncSettings & sync,float)192     virtual status_t    setSyncSettings(const AVSyncSettings& sync, float /* videoFps */) {
193         // By default, players only support setting sync source to default; all other sync
194         // settings are ignored. There is no requirement for getters to return set values.
195         if (sync.mSource != AVSYNC_SOURCE_DEFAULT) {
196             return BAD_VALUE;
197         }
198         return OK;
199     }
getSyncSettings(AVSyncSettings * sync,float * videoFps)200     virtual status_t    getSyncSettings(
201                                 AVSyncSettings* sync /* nonnull */, float* videoFps /* nonnull */) {
202         *sync = AVSyncSettings();
203         *videoFps = -1.f;
204         return OK;
205     }
206     virtual status_t    seekTo(int msec) = 0;
207     virtual status_t    getCurrentPosition(int *msec) = 0;
208     virtual status_t    getDuration(int *msec) = 0;
209     virtual status_t    reset() = 0;
210     virtual status_t    setLooping(int loop) = 0;
211     virtual player_type playerType() = 0;
212     virtual status_t    setParameter(int key, const Parcel &request) = 0;
213     virtual status_t    getParameter(int key, Parcel *reply) = 0;
214 
215     // default no-op implementation of optional extensions
setRetransmitEndpoint(const struct sockaddr_in *)216     virtual status_t setRetransmitEndpoint(const struct sockaddr_in* /* endpoint */) {
217         return INVALID_OPERATION;
218     }
getRetransmitEndpoint(struct sockaddr_in *)219     virtual status_t getRetransmitEndpoint(struct sockaddr_in* /* endpoint */) {
220         return INVALID_OPERATION;
221     }
setNextPlayer(const sp<MediaPlayerBase> &)222     virtual status_t setNextPlayer(const sp<MediaPlayerBase>& /* next */) {
223         return OK;
224     }
225 
226     // Invoke a generic method on the player by using opaque parcels
227     // for the request and reply.
228     //
229     // @param request Parcel that is positioned at the start of the
230     //                data sent by the java layer.
231     // @param[out] reply Parcel to hold the reply data. Cannot be null.
232     // @return OK if the call was successful.
233     virtual status_t    invoke(const Parcel& request, Parcel *reply) = 0;
234 
235     // The Client in the MetadataPlayerService calls this method on
236     // the native player to retrieve all or a subset of metadata.
237     //
238     // @param ids SortedList of metadata ID to be fetch. If empty, all
239     //            the known metadata should be returned.
240     // @param[inout] records Parcel where the player appends its metadata.
241     // @return OK if the call was successful.
getMetadata(const media::Metadata::Filter &,Parcel *)242     virtual status_t    getMetadata(const media::Metadata::Filter& /* ids */,
243                                     Parcel* /* records */) {
244         return INVALID_OPERATION;
245     };
246 
setNotifyCallback(void * cookie,notify_callback_f notifyFunc)247     void        setNotifyCallback(
248             void* cookie, notify_callback_f notifyFunc) {
249         Mutex::Autolock autoLock(mNotifyLock);
250         mCookie = cookie; mNotify = notifyFunc;
251     }
252 
253     void        sendEvent(int msg, int ext1=0, int ext2=0,
254                           const Parcel *obj=NULL) {
255         notify_callback_f notifyCB;
256         void* cookie;
257         {
258             Mutex::Autolock autoLock(mNotifyLock);
259             notifyCB = mNotify;
260             cookie = mCookie;
261         }
262 
263         if (notifyCB) notifyCB(cookie, msg, ext1, ext2, obj);
264     }
265 
dump(int,const Vector<String16> &)266     virtual status_t dump(int /* fd */, const Vector<String16>& /* args */) const {
267         return INVALID_OPERATION;
268     }
269 
270 private:
271     friend class MediaPlayerService;
272 
273     Mutex               mNotifyLock;
274     void*               mCookie;
275     notify_callback_f   mNotify;
276 };
277 
278 // Implement this class for media players that use the AudioFlinger software mixer
279 class MediaPlayerInterface : public MediaPlayerBase
280 {
281 public:
~MediaPlayerInterface()282     virtual             ~MediaPlayerInterface() { }
hardwareOutput()283     virtual bool        hardwareOutput() { return false; }
setAudioSink(const sp<AudioSink> & audioSink)284     virtual void        setAudioSink(const sp<AudioSink>& audioSink) { mAudioSink = audioSink; }
285 protected:
286     sp<AudioSink>       mAudioSink;
287 };
288 
289 // Implement this class for media players that output audio directly to hardware
290 class MediaPlayerHWInterface : public MediaPlayerBase
291 {
292 public:
~MediaPlayerHWInterface()293     virtual             ~MediaPlayerHWInterface() {}
hardwareOutput()294     virtual bool        hardwareOutput() { return true; }
295     virtual status_t    setVolume(float leftVolume, float rightVolume) = 0;
296     virtual status_t    setAudioStreamType(audio_stream_type_t streamType) = 0;
297 };
298 
299 }; // namespace android
300 
301 #endif // __cplusplus
302 
303 
304 #endif // ANDROID_MEDIAPLAYERINTERFACE_H
305