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