LiveSession.h revision 404fced9bfa8fa423ee210a271ca051ffd1bec13
1/*
2 * Copyright (C) 2010 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 LIVE_SESSION_H_
18
19#define LIVE_SESSION_H_
20
21#include <media/stagefright/foundation/AHandler.h>
22
23#include <utils/String8.h>
24
25namespace android {
26
27struct ABuffer;
28struct AnotherPacketSource;
29struct DataSource;
30struct HTTPBase;
31struct IMediaHTTPService;
32struct LiveDataSource;
33struct M3UParser;
34struct PlaylistFetcher;
35struct Parcel;
36
37struct LiveSession : public AHandler {
38    enum Flags {
39        // Don't log any URLs.
40        kFlagIncognito = 1,
41    };
42    LiveSession(
43            const sp<AMessage> &notify,
44            uint32_t flags,
45            const sp<IMediaHTTPService> &httpService);
46
47    enum StreamIndex {
48        kAudioIndex    = 0,
49        kVideoIndex    = 1,
50        kSubtitleIndex = 2,
51        kMaxStreams    = 3,
52    };
53
54    enum StreamType {
55        STREAMTYPE_AUDIO        = 1 << kAudioIndex,
56        STREAMTYPE_VIDEO        = 1 << kVideoIndex,
57        STREAMTYPE_SUBTITLES    = 1 << kSubtitleIndex,
58    };
59    status_t dequeueAccessUnit(StreamType stream, sp<ABuffer> *accessUnit);
60
61    status_t getStreamFormat(StreamType stream, sp<AMessage> *format);
62
63    void connectAsync(
64            const char *url,
65            const KeyedVector<String8, String8> *headers = NULL);
66
67    status_t disconnect();
68
69    // Blocks until seek is complete.
70    status_t seekTo(int64_t timeUs);
71
72    status_t getDuration(int64_t *durationUs) const;
73    size_t getTrackCount() const;
74    sp<AMessage> getTrackInfo(size_t trackIndex) const;
75    status_t selectTrack(size_t index, bool select);
76
77    bool isSeekable() const;
78    bool hasDynamicDuration() const;
79
80    enum {
81        kWhatStreamsChanged,
82        kWhatError,
83        kWhatPrepared,
84        kWhatPreparationFailed,
85    };
86
87    // create a format-change discontinuity
88    //
89    // swap:
90    //   whether is format-change discontinuity should trigger a buffer swap
91    sp<ABuffer> createFormatChangeBuffer(bool swap = true);
92protected:
93    virtual ~LiveSession();
94
95    virtual void onMessageReceived(const sp<AMessage> &msg);
96
97private:
98    friend struct PlaylistFetcher;
99
100    enum {
101        kWhatConnect                    = 'conn',
102        kWhatDisconnect                 = 'disc',
103        kWhatSeek                       = 'seek',
104        kWhatFetcherNotify              = 'notf',
105        kWhatCheckBandwidth             = 'bndw',
106        kWhatChangeConfiguration        = 'chC0',
107        kWhatChangeConfiguration2       = 'chC2',
108        kWhatChangeConfiguration3       = 'chC3',
109        kWhatFinishDisconnect2          = 'fin2',
110        kWhatSwapped                    = 'swap',
111    };
112
113    struct BandwidthItem {
114        size_t mPlaylistIndex;
115        unsigned long mBandwidth;
116    };
117
118    struct FetcherInfo {
119        sp<PlaylistFetcher> mFetcher;
120        int64_t mDurationUs;
121        bool mIsPrepared;
122        bool mToBeRemoved;
123    };
124
125    struct StreamItem {
126        const char *mType;
127        AString mUri;
128        StreamItem() : mType("") {}
129        StreamItem(const char *type) : mType(type) {}
130        AString uriKey() {
131            AString key(mType);
132            key.append("URI");
133            return key;
134        }
135    };
136    StreamItem mStreams[kMaxStreams];
137
138    sp<AMessage> mNotify;
139    uint32_t mFlags;
140    sp<IMediaHTTPService> mHTTPService;
141
142    bool mInPreparationPhase;
143
144    sp<HTTPBase> mHTTPDataSource;
145    KeyedVector<String8, String8> mExtraHeaders;
146
147    AString mMasterURL;
148
149    Vector<BandwidthItem> mBandwidthItems;
150    ssize_t mPrevBandwidthIndex;
151
152    sp<M3UParser> mPlaylist;
153
154    KeyedVector<AString, FetcherInfo> mFetcherInfos;
155    uint32_t mStreamMask;
156
157    // Masks used during reconfiguration:
158    // mNewStreamMask: streams in the variant playlist we're switching to;
159    // we don't want to immediately overwrite the original value.
160    uint32_t mNewStreamMask;
161
162    // mSwapMask: streams that have started to playback content in the new variant playlist;
163    // we use this to track reconfiguration progress.
164    uint32_t mSwapMask;
165
166    KeyedVector<StreamType, sp<AnotherPacketSource> > mPacketSources;
167    // A second set of packet sources that buffer content for the variant we're switching to.
168    KeyedVector<StreamType, sp<AnotherPacketSource> > mPacketSources2;
169
170    // A mutex used to serialize two sets of events:
171    // * the swapping of packet sources in dequeueAccessUnit on the player thread, AND
172    // * a forced bandwidth switch termination in cancelSwitch on the live looper.
173    Mutex mSwapMutex;
174
175    int32_t mCheckBandwidthGeneration;
176    int32_t mSwitchGeneration;
177
178    size_t mContinuationCounter;
179    sp<AMessage> mContinuation;
180    sp<AMessage> mSeekReply;
181
182    int64_t mLastDequeuedTimeUs;
183    int64_t mRealTimeBaseUs;
184
185    bool mReconfigurationInProgress;
186    bool mSwitchInProgress;
187    uint32_t mDisconnectReplyID;
188    uint32_t mSeekReplyID;
189
190    sp<PlaylistFetcher> addFetcher(const char *uri);
191
192    void onConnect(const sp<AMessage> &msg);
193    status_t onSeek(const sp<AMessage> &msg);
194    void onFinishDisconnect2();
195
196    // If given a non-zero block_size (default 0), it is used to cap the number of
197    // bytes read in from the DataSource. If given a non-NULL buffer, new content
198    // is read into the end.
199    //
200    // The DataSource we read from is responsible for signaling error or EOF to help us
201    // break out of the read loop. The DataSource can be returned to the caller, so
202    // that the caller can reuse it for subsequent fetches (within the initially
203    // requested range).
204    //
205    // For reused HTTP sources, the caller must download a file sequentially without
206    // any overlaps or gaps to prevent reconnection.
207    ssize_t fetchFile(
208            const char *url, sp<ABuffer> *out,
209            /* request/open a file starting at range_offset for range_length bytes */
210            int64_t range_offset = 0, int64_t range_length = -1,
211            /* download block size */
212            uint32_t block_size = 0,
213            /* reuse DataSource if doing partial fetch */
214            sp<DataSource> *source = NULL,
215            String8 *actualUrl = NULL);
216
217    sp<M3UParser> fetchPlaylist(
218            const char *url, uint8_t *curPlaylistHash, bool *unchanged);
219
220    size_t getBandwidthIndex();
221
222    static int SortByBandwidth(const BandwidthItem *, const BandwidthItem *);
223    static StreamType indexToType(int idx);
224
225    void changeConfiguration(
226            int64_t timeUs, size_t bandwidthIndex, bool pickTrack = false);
227    void onChangeConfiguration(const sp<AMessage> &msg);
228    void onChangeConfiguration2(const sp<AMessage> &msg);
229    void onChangeConfiguration3(const sp<AMessage> &msg);
230    void onSwapped(const sp<AMessage> &msg);
231    void tryToFinishBandwidthSwitch();
232
233    void scheduleCheckBandwidthEvent();
234    void cancelCheckBandwidthEvent();
235
236    // cancelBandwidthSwitch is atomic wrt swapPacketSource; call it to prevent packet sources
237    // from being swapped out on stale discontinuities while manipulating
238    // mPacketSources/mPacketSources2.
239    void cancelBandwidthSwitch();
240
241    bool canSwitchBandwidthTo(size_t bandwidthIndex);
242    void onCheckBandwidth();
243
244    void finishDisconnect();
245
246    void postPrepared(status_t err);
247
248    void swapPacketSource(StreamType stream);
249    bool canSwitchUp();
250
251    DISALLOW_EVIL_CONSTRUCTORS(LiveSession);
252};
253
254}  // namespace android
255
256#endif  // LIVE_SESSION_H_
257