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