GenericSource.h revision 5249a5583df9a17dc3899100ea642f29eb86a23e
1/*
2 * Copyright (C) 2012 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 GENERIC_SOURCE_H_
18
19#define GENERIC_SOURCE_H_
20
21#include "NuPlayer.h"
22#include "NuPlayerSource.h"
23
24#include "ATSParser.h"
25
26#include <media/mediaplayer.h>
27
28namespace android {
29
30class DecryptHandle;
31class DrmManagerClient;
32struct AnotherPacketSource;
33struct ARTSPController;
34class DataSource;
35class IDataSource;
36struct IMediaHTTPService;
37struct MediaSource;
38class MediaBuffer;
39struct NuCachedSource2;
40
41struct NuPlayer::GenericSource : public NuPlayer::Source {
42    GenericSource(const sp<AMessage> &notify, bool uidValid, uid_t uid);
43
44    status_t setDataSource(
45            const sp<IMediaHTTPService> &httpService,
46            const char *url,
47            const KeyedVector<String8, String8> *headers);
48
49    status_t setDataSource(int fd, int64_t offset, int64_t length);
50
51    status_t setDataSource(const sp<DataSource>& dataSource);
52
53    virtual void prepareAsync();
54
55    virtual void start();
56    virtual void stop();
57    virtual void pause();
58    virtual void resume();
59
60    virtual void disconnect();
61
62    virtual status_t feedMoreTSData();
63
64    virtual sp<MetaData> getFileFormatMeta() const;
65
66    virtual status_t dequeueAccessUnit(bool audio, sp<ABuffer> *accessUnit);
67
68    virtual status_t getDuration(int64_t *durationUs);
69    virtual size_t getTrackCount() const;
70    virtual sp<AMessage> getTrackInfo(size_t trackIndex) const;
71    virtual ssize_t getSelectedTrack(media_track_type type) const;
72    virtual status_t selectTrack(size_t trackIndex, bool select, int64_t timeUs);
73    virtual status_t seekTo(
74        int64_t seekTimeUs,
75        MediaPlayerSeekMode mode = MediaPlayerSeekMode::SEEK_PREVIOUS_SYNC) override;
76
77    virtual status_t setBuffers(bool audio, Vector<MediaBuffer *> &buffers);
78
79    virtual bool isStreaming() const;
80
81    virtual void setOffloadAudio(bool offload);
82
83protected:
84    virtual ~GenericSource();
85
86    virtual void onMessageReceived(const sp<AMessage> &msg);
87
88    virtual sp<MetaData> getFormatMeta(bool audio);
89
90private:
91    enum {
92        kWhatPrepareAsync,
93        kWhatFetchSubtitleData,
94        kWhatFetchTimedTextData,
95        kWhatSendSubtitleData,
96        kWhatSendGlobalTimedTextData,
97        kWhatSendTimedTextData,
98        kWhatChangeAVSource,
99        kWhatPollBuffering,
100        kWhatGetFormat,
101        kWhatGetSelectedTrack,
102        kWhatSelectTrack,
103        kWhatSeek,
104        kWhatReadBuffer,
105        kWhatStart,
106        kWhatResume,
107        kWhatSecureDecodersInstantiated,
108    };
109
110    struct Track {
111        size_t mIndex;
112        sp<IMediaSource> mSource;
113        sp<AnotherPacketSource> mPackets;
114    };
115
116    // Helper to monitor buffering status. The polling happens every second.
117    // When necessary, it will send out buffering events to the player.
118    struct BufferingMonitor : public AHandler {
119    public:
120        explicit BufferingMonitor(const sp<AMessage> &notify);
121
122        // Set up state.
123        void prepare(const sp<NuCachedSource2> &cachedSource,
124                int64_t durationUs,
125                int64_t bitrate,
126                bool isStreaming);
127        // Stop and reset buffering monitor.
128        void stop();
129        // Cancel the current monitor task.
130        void cancelPollBuffering();
131        // Restart the monitor task.
132        void restartPollBuffering();
133        // Stop buffering task and send out corresponding events.
134        void stopBufferingIfNecessary();
135        // Make sure data source is getting data.
136        void ensureCacheIsFetching();
137        // Update media time of just extracted buffer from data source.
138        void updateQueuedTime(bool isAudio, int64_t timeUs);
139
140        // Set the offload mode.
141        void setOffloadAudio(bool offload);
142        // Update media time of last dequeued buffer which is sent to the decoder.
143        void updateDequeuedBufferTime(int64_t mediaUs);
144
145    protected:
146        virtual ~BufferingMonitor();
147        virtual void onMessageReceived(const sp<AMessage> &msg);
148
149    private:
150        enum {
151            kWhatPollBuffering,
152        };
153
154        sp<AMessage> mNotify;
155
156        sp<NuCachedSource2> mCachedSource;
157        int64_t mDurationUs;
158        int64_t mBitrate;
159        bool mIsStreaming;
160
161        int64_t mAudioTimeUs;
162        int64_t mVideoTimeUs;
163        int32_t mPollBufferingGeneration;
164        bool mPrepareBuffering;
165        bool mBuffering;
166        int32_t mPrevBufferPercentage;
167
168        mutable Mutex mLock;
169
170        bool mOffloadAudio;
171        int64_t mFirstDequeuedBufferRealUs;
172        int64_t mFirstDequeuedBufferMediaUs;
173        int64_t mlastDequeuedBufferMediaUs;
174
175        void prepare_l(const sp<NuCachedSource2> &cachedSource,
176                int64_t durationUs,
177                int64_t bitrate,
178                bool isStreaming);
179        void cancelPollBuffering_l();
180        void notifyBufferingUpdate_l(int32_t percentage);
181        void startBufferingIfNecessary_l();
182        void stopBufferingIfNecessary_l();
183        void sendCacheStats_l();
184        void ensureCacheIsFetching_l();
185        int64_t getLastReadPosition_l();
186        void onPollBuffering_l();
187        void schedulePollBuffering_l();
188    };
189
190    Vector<sp<IMediaSource> > mSources;
191    Track mAudioTrack;
192    int64_t mAudioTimeUs;
193    int64_t mAudioLastDequeueTimeUs;
194    Track mVideoTrack;
195    int64_t mVideoTimeUs;
196    int64_t mVideoLastDequeueTimeUs;
197    Track mSubtitleTrack;
198    Track mTimedTextTrack;
199
200    int32_t mFetchSubtitleDataGeneration;
201    int32_t mFetchTimedTextDataGeneration;
202    int64_t mDurationUs;
203    bool mAudioIsVorbis;
204    bool mIsSecure;
205    bool mIsStreaming;
206    bool mUIDValid;
207    uid_t mUID;
208    sp<IMediaHTTPService> mHTTPService;
209    AString mUri;
210    KeyedVector<String8, String8> mUriHeaders;
211    int mFd;
212    int64_t mOffset;
213    int64_t mLength;
214
215    sp<DataSource> mDataSource;
216    sp<NuCachedSource2> mCachedSource;
217    sp<DataSource> mHttpSource;
218    sp<MetaData> mFileMeta;
219    DrmManagerClient *mDrmManagerClient;
220    sp<DecryptHandle> mDecryptHandle;
221    bool mStarted;
222    bool mStopRead;
223    int64_t mBitrate;
224    sp<BufferingMonitor> mBufferingMonitor;
225    uint32_t mPendingReadBufferTypes;
226    sp<ABuffer> mGlobalTimedText;
227
228    mutable Mutex mReadBufferLock;
229    mutable Mutex mDisconnectLock;
230
231    sp<ALooper> mLooper;
232    sp<ALooper> mBufferingMonitorLooper;
233
234    void resetDataSource();
235
236    status_t initFromDataSource();
237    int64_t getLastReadPosition();
238    void setDrmPlaybackStatusIfNeeded(int playbackStatus, int64_t position);
239
240    void notifyPreparedAndCleanup(status_t err);
241    void onSecureDecodersInstantiated(status_t err);
242    void finishPrepareAsync();
243    status_t startSources();
244
245    void onGetFormatMeta(const sp<AMessage>& msg) const;
246    sp<MetaData> doGetFormatMeta(bool audio) const;
247
248    void onGetSelectedTrack(const sp<AMessage>& msg) const;
249    ssize_t doGetSelectedTrack(media_track_type type) const;
250
251    void onSelectTrack(const sp<AMessage>& msg);
252    status_t doSelectTrack(size_t trackIndex, bool select, int64_t timeUs);
253
254    void onSeek(const sp<AMessage>& msg);
255    status_t doSeek(int64_t seekTimeUs, MediaPlayerSeekMode mode);
256
257    void onPrepareAsync();
258
259    void fetchTextData(
260            uint32_t what, media_track_type type,
261            int32_t curGen, const sp<AnotherPacketSource>& packets, const sp<AMessage>& msg);
262
263    void sendGlobalTextData(
264            uint32_t what,
265            int32_t curGen, sp<AMessage> msg);
266
267    void sendTextData(
268            uint32_t what, media_track_type type,
269            int32_t curGen, const sp<AnotherPacketSource>& packets, const sp<AMessage>& msg);
270
271    sp<ABuffer> mediaBufferToABuffer(
272            MediaBuffer *mbuf,
273            media_track_type trackType);
274
275    void postReadBuffer(media_track_type trackType);
276    void onReadBuffer(const sp<AMessage>& msg);
277    // When |mode| is MediaPlayerSeekMode::SEEK_CLOSEST, the buffer read shall
278    // include an item indicating skipping rendering all buffers with timestamp
279    // earlier than |seekTimeUs|.
280    // For other modes, the buffer read will not include the item as above in order
281    // to facilitate fast seek operation.
282    void readBuffer(
283            media_track_type trackType,
284            int64_t seekTimeUs = -1ll,
285            MediaPlayerSeekMode mode = MediaPlayerSeekMode::SEEK_PREVIOUS_SYNC,
286            int64_t *actualTimeUs = NULL, bool formatChange = false);
287
288    void queueDiscontinuityIfNeeded(
289            bool seeking, bool formatChange, media_track_type trackType, Track *track);
290
291    DISALLOW_EVIL_CONSTRUCTORS(GenericSource);
292};
293
294}  // namespace android
295
296#endif  // GENERIC_SOURCE_H_
297