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