PlaylistFetcher.h revision 25f82752942b1c78aec8ee303d61afff85cff9d1
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 PLAYLIST_FETCHER_H_
18
19#define PLAYLIST_FETCHER_H_
20
21#include <media/stagefright/foundation/AHandler.h>
22
23#include "mpeg2ts/ATSParser.h"
24#include "LiveSession.h"
25
26namespace android {
27
28struct ABuffer;
29struct AnotherPacketSource;
30struct DataSource;
31struct HTTPBase;
32struct LiveDataSource;
33struct M3UParser;
34class String8;
35
36struct PlaylistFetcher : public AHandler {
37    static const int64_t kMinBufferedDurationUs;
38    static const int32_t kDownloadBlockSize;
39    static const int64_t kFetcherResumeThreshold;
40
41    enum {
42        kWhatStarted,
43        kWhatPaused,
44        kWhatStopped,
45        kWhatError,
46        kWhatDurationUpdate,
47        kWhatTargetDurationUpdate,
48        kWhatPrepared,
49        kWhatPreparationFailed,
50        kWhatStartedAt,
51        kWhatStopReached,
52    };
53
54    PlaylistFetcher(
55            const sp<AMessage> &notify,
56            const sp<LiveSession> &session,
57            const char *uri,
58            int32_t id,
59            int32_t subtitleGeneration);
60
61    int32_t getFetcherID() const;
62
63    sp<DataSource> getDataSource();
64
65    void startAsync(
66            const sp<AnotherPacketSource> &audioSource,
67            const sp<AnotherPacketSource> &videoSource,
68            const sp<AnotherPacketSource> &subtitleSource,
69            int64_t startTimeUs = -1ll,         // starting timestamps
70            int64_t segmentStartTimeUs = -1ll, // starting position within playlist
71            // startTimeUs!=segmentStartTimeUs only when playlist is live
72            int32_t startDiscontinuitySeq = -1,
73            LiveSession::SeekMode seekMode = LiveSession::kSeekModeExactPosition);
74
75    void pauseAsync(float thresholdRatio);
76
77    void stopAsync(bool clear = true);
78
79    void resumeUntilAsync(const sp<AMessage> &params);
80
81    uint32_t getStreamTypeMask() const {
82        return mStreamTypeMask;
83    }
84
85protected:
86    virtual ~PlaylistFetcher();
87    virtual void onMessageReceived(const sp<AMessage> &msg);
88
89private:
90    enum {
91        kMaxNumRetries         = 5,
92    };
93
94    enum {
95        kWhatStart          = 'strt',
96        kWhatPause          = 'paus',
97        kWhatStop           = 'stop',
98        kWhatMonitorQueue   = 'moni',
99        kWhatResumeUntil    = 'rsme',
100        kWhatDownloadNext   = 'dlnx',
101    };
102
103    struct DownloadState;
104
105    static const int64_t kMaxMonitorDelayUs;
106    static const int32_t kNumSkipFrames;
107
108    static bool bufferStartsWithTsSyncByte(const sp<ABuffer>& buffer);
109    static bool bufferStartsWithWebVTTMagicSequence(const sp<ABuffer>& buffer);
110
111    // notifications to mSession
112    sp<AMessage> mNotify;
113    sp<AMessage> mStartTimeUsNotify;
114
115    sp<HTTPBase> mHTTPDataSource;
116    sp<LiveSession> mSession;
117    AString mURI;
118
119    int32_t mFetcherID;
120
121    uint32_t mStreamTypeMask;
122    int64_t mStartTimeUs;
123
124    // Start time relative to the beginning of the first segment in the initial
125    // playlist. It's value is initialized to a non-negative value only when we are
126    // adapting or switching tracks.
127    int64_t mSegmentStartTimeUs;
128
129    int32_t mDiscontinuitySeq;
130    bool mStartTimeUsRelative;
131    sp<AMessage> mStopParams; // message containing the latest timestamps we should fetch.
132
133    KeyedVector<LiveSession::StreamType, sp<AnotherPacketSource> >
134        mPacketSources;
135
136    KeyedVector<AString, sp<ABuffer> > mAESKeyForURI;
137
138    int64_t mLastPlaylistFetchTimeUs;
139    sp<M3UParser> mPlaylist;
140    int32_t mSeqNumber;
141    int32_t mNumRetries;
142    bool mStartup;
143    bool mIDRFound;
144    int32_t mSeekMode;
145    bool mTimeChangeSignaled;
146    int64_t mNextPTSTimeUs;
147
148    int32_t mMonitorQueueGeneration;
149    const int32_t mSubtitleGeneration;
150
151    int32_t mLastDiscontinuitySeq;
152
153    enum RefreshState {
154        INITIAL_MINIMUM_RELOAD_DELAY,
155        FIRST_UNCHANGED_RELOAD_ATTEMPT,
156        SECOND_UNCHANGED_RELOAD_ATTEMPT,
157        THIRD_UNCHANGED_RELOAD_ATTEMPT
158    };
159    RefreshState mRefreshState;
160
161    uint8_t mPlaylistHash[16];
162
163    sp<ATSParser> mTSParser;
164
165    bool mFirstPTSValid;
166    int64_t mFirstTimeUs;
167    int64_t mSegmentFirstPTS;
168    sp<AnotherPacketSource> mVideoBuffer;
169
170    // Stores the initialization vector to decrypt the next block of cipher text, which can
171    // either be derived from the sequence number, read from the manifest, or copied from
172    // the last block of cipher text (cipher-block chaining).
173    unsigned char mAESInitVec[16];
174
175    Mutex mThresholdLock;
176    float mThresholdRatio;
177
178    sp<DownloadState> mDownloadState;
179
180    // Set first to true if decrypting the first segment of a playlist segment. When
181    // first is true, reset the initialization vector based on the available
182    // information in the manifest; otherwise, use the initialization vector as
183    // updated by the last call to AES_cbc_encrypt.
184    //
185    // For the input to decrypt correctly, decryptBuffer must be called on
186    // consecutive byte ranges on block boundaries, e.g. 0..15, 16..47, 48..63,
187    // and so on.
188    status_t decryptBuffer(
189            size_t playlistIndex, const sp<ABuffer> &buffer,
190            bool first = true);
191    status_t checkDecryptPadding(const sp<ABuffer> &buffer);
192
193    void postMonitorQueue(int64_t delayUs = 0, int64_t minDelayUs = 0);
194    void cancelMonitorQueue();
195    void setStoppingThreshold(float thresholdRatio);
196    bool shouldPauseDownload();
197
198    int64_t delayUsToRefreshPlaylist() const;
199    status_t refreshPlaylist();
200
201    // Returns the media time in us of the segment specified by seqNumber.
202    // This is computed by summing the durations of all segments before it.
203    int64_t getSegmentStartTimeUs(int32_t seqNumber) const;
204    // Returns the duration time in us of the segment specified.
205    int64_t getSegmentDurationUs(int32_t seqNumber) const;
206
207    status_t onStart(const sp<AMessage> &msg);
208    void onPause();
209    void onStop(const sp<AMessage> &msg);
210    void onMonitorQueue();
211    void onDownloadNext();
212    bool initDownloadState(
213            AString &uri,
214            sp<AMessage> &itemMeta,
215            int32_t &firstSeqNumberInPlaylist,
216            int32_t &lastSeqNumberInPlaylist);
217
218    // Resume a fetcher to continue until the stopping point stored in msg.
219    status_t onResumeUntil(const sp<AMessage> &msg);
220
221    const sp<ABuffer> &setAccessUnitProperties(
222            const sp<ABuffer> &accessUnit,
223            const sp<AnotherPacketSource> &source,
224            bool discard = false);
225    status_t extractAndQueueAccessUnitsFromTs(const sp<ABuffer> &buffer);
226
227    status_t extractAndQueueAccessUnits(
228            const sp<ABuffer> &buffer, const sp<AMessage> &itemMeta);
229
230    void notifyStopReached();
231    void notifyError(status_t err);
232
233    void queueDiscontinuity(
234            ATSParser::DiscontinuityType type, const sp<AMessage> &extra);
235
236    int32_t getSeqNumberWithAnchorTime(
237            int64_t anchorTimeUs, int64_t targetDurationUs) const;
238    int32_t getSeqNumberForDiscontinuity(size_t discontinuitySeq) const;
239    int32_t getSeqNumberForTime(int64_t timeUs) const;
240
241    void updateDuration();
242    void updateTargetDuration();
243
244    DISALLOW_EVIL_CONSTRUCTORS(PlaylistFetcher);
245};
246
247}  // namespace android
248
249#endif  // PLAYLIST_FETCHER_H_
250
251