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