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